PHP code example of pavelzanek / laravel-deepl

1. Go to this page and download the library: Download pavelzanek/laravel-deepl library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pavelzanek / laravel-deepl example snippets


use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText('Hello, world!', 'en', 'de');

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

$translatedText = $client->translateText('Hello, world!', 'en', 'de');

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText('Hello, world!', 'en', 'de');

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

$translatedText = $client->translateText('Hello, world!', 'en', 'de');

echo $translatedText; // Outputs: Hallo, Welt!



namespace App\Http\Controllers;

use PavelZanek\LaravelDeepl\DeeplClient;

class TestController extends Controller
{
    public function __construct(
        protected readonly DeeplClient $deeplClient
    ) {}

    public function translateText(): void
    {
        $translation = $this->deeplClient->translateText(
            texts: 'Ahoj, jak se máš?',
            sourceLang: 'cs',
            targetLang: 'en-gb'
        );
    
        dd($translation);

        //    DeepL\TextResult {
        //        +text: "Hey, how are you?"
        //        +detectedSourceLang: "cs"
        //        +billedCharacters: 17
        //    }

        $translation = $this->deeplClient->translateText(
            texts: ['Ahoj, jak se máš?', 'Mám se dobře, jak se máš ty?'],
            sourceLang: 'cs',
            targetLang: 'en-gb'
        );

        dd($translation);

        //    array [
        //        0 => DeepL\TextResult {
        //            +text: "Hey, how are you?"
        //            +detectedSourceLang: "cs"
        //            +billedCharacters: 17
        //        }
        //        1 => DeepL\TextResult {
        //            +text: "I'm fine, how are you?"
        //            +detectedSourceLang: "cs"
        //            +billedCharacters: 28
        //        }
        //    ]
    }
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->formality('less')
    ->preserveFormatting('enabled')
    ->splitSentences('1')
    ->glossary('example-glossary-id')
    ->withoutCache()
    ->translate();

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

$translatedText = $client->translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->formality('less')
    ->preserveFormatting('enabled')
    ->splitSentences('1')
    ->glossary('example-glossary-id')
    ->withoutCache()
    ->translate();

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText(
    'Hello, world!',
    'en',
    'de',
    [
        'formality' => 'less',
        'preserve_formatting' => 'enabled',
        'split_sentences' => '1',
        'glossary_id' => 'example-glossary-id',
    ],
)->translate();

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->options([
        'formality' => 'less',
        'preserve_formatting' => 'enabled',
        'split_sentences' => '1',
        'glossary_id' => 'example-glossary-id',
    ])
    ->translate();
    
echo $translatedText; // Outputs: Hallo, Welt!

// config/laravel-deepl.php

return [
    // ...
    'enable_translation_cache' => env('DEEPL_ENABLE_TRANSLATION_CACHE', false),
    'translation_cache_table' => env('DEEPL_TRANSLATION_CACHE_TABLE', 'translations_cache'),
    // ...
];

$translatedText = $client->translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->translate();

$translatedText = $client->translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->formality('less')
    ->translate();

use PavelZanek\LaravelDeepl\DeeplClient;

$client = new DeeplClient();

$translatedText = $client->translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->translate();

echo $translatedText; // Outputs: Hallo, Welt! (from cache or API)

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText(
    'Hello, world!',
    'en',
    'de',
    [],        // No additional options
    false      // Disables cache usage for this request
)->translate();

// or if u prefer named parameters
$translatedText = Deepl::translateText(
    text: 'Hello, world!',
    sourceLang: 'en',
    targetLang: 'de',
    useCache: false     // Disables cache usage for this request
)->translate();

echo $translatedText; // Always fetches from API

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->withoutCache() // Disables cache usage for this request
    ->translate();

echo $translatedText; // Always fetches from API

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedText = Deepl::translateText()
    ->text('Hello, world!')
    ->sourceLang('en')
    ->targetLang('de')
    ->translate();

echo $translatedText; // Outputs: Hallo, Welt!

use PavelZanek\LaravelDeepl\Facades\Deepl;

$translatedTexts = Deepl::translateText()
    ->texts(['Hello, world!', 'Good morning!'])
    ->sourceLang('en')
    ->targetLang('de')
    ->translate();

foreach ($translatedTexts as $translatedText) {
    echo $translatedText->text . "\n"; // Outputs: Hallo, Welt! and Guten Morgen!
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

// Upload the document for translation
$uploadResponse = Deepl::uploadDocument('path/to/document.pdf', 'de');

// Check the status of the translation
$status = Deepl::getDocumentStatus($uploadResponse['document_id'], $uploadResponse['document_key']);

if ($status->status === \PavelZanek\LaravelDeepl\Enums\V2\DocumentStatus::DONE->value) {
    // Download the translated document
    $translatedDocument = Deepl::downloadDocument($uploadResponse['document_id'], $uploadResponse['document_key']);
    file_put_contents('path/to/translated-document.pdf', $translatedDocument);
}

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

// Upload the document for translation
$uploadResponse = $client->uploadDocument('path/to/document.pdf', 'de');

// Check the status of the translation
$status = $client->getDocumentStatus($uploadResponse['document_id'], $uploadResponse['document_key']);

if ($status->status === \PavelZanek\LaravelDeepl\Enums\V2\DocumentStatus::DONE->value) {
    // Download the translated document
    $translatedDocument = $client->downloadDocument($uploadResponse['document_id'], $uploadResponse['document_key']);
    file_put_contents('path/to/translated-document.pdf', $translatedDocument);
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

// Perform a document translation with chainable methods
$status = Deepl::translateDocumentBuilder()
    ->inputFile('path/to/input.docx')
    ->outputFile('path/to/output.docx')
    ->sourceLang('en')
    ->targetLang('de')
    ->enableMinification()
    ->options([
        'formality' => 'more',
        // Add other options as needed
    ])
    ->translate();

echo $status->status; // Outputs: done, translating, etc.

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

// Perform a document translation with chainable methods
$status = $client->translateDocumentBuilder()
    ->inputFile('path/to/input.pdf')
    ->outputFile('path/to/output.pdf')
    ->sourceLang('en')
    ->targetLang('fr')
    ->translate();

echo $status->status; // Outputs: done, translating, etc.

$client->translateDocument(
    'path/to/input.docx',
    'path/to/output.docx',
    'en',
    'de',
    [
        'formality' => 'more',
        \DeepL\TranslateDocumentOptions::ENABLE_DOCUMENT_MINIFICATION => true,
    ]
);

use PavelZanek\LaravelDeepl\Facades\Deepl;

// Create a glossary
$glossary = Deepl::createGlossary(
    'My Glossary',
    'en',
    'de',
    [
        'hello' => 'hallo',
        'world' => 'welt',
    ]
);

// Retrieve glossary details
$glossaryDetails = Deepl::getGlossary($glossary->glossaryId);

// Delete a glossary
Deepl::deleteGlossary($glossary->glossaryId);

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

// Create a glossary
$glossary = $client->createGlossary(
    'My Glossary',
    'en',
    'de',
    [
        'hello' => 'hallo',
        'world' => 'welt',
    ]
);

// Retrieve glossary details
$glossaryDetails = $client->getGlossary($glossary->glossaryId);

// Delete a glossary
$client->deleteGlossary($glossary->glossaryId);

use PavelZanek\LaravelDeepl\Facades\Deepl;

try {
    $glossaryInfo = Deepl::createGlossaryBuilder()
        ->name('My Glossary')
        ->sourceLang('en')
        ->targetLang('de')
        ->addEntry('artist', 'Künstler')
        ->addEntry('prize', 'Preis')
        ->create();

    echo "Created '{$glossaryInfo->name}' ({$glossaryInfo->glossaryId}) ";
    echo "{$glossaryInfo->sourceLang} to {$glossaryInfo->targetLang} ";
    echo "containing {$glossaryInfo->entryCount} entries\n";
} catch (\Exception $e) {
    echo "Error creating glossary: " . $e->getMessage();
}

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

try {
    $glossaryInfo = $client->createGlossaryBuilder()
        ->name('My Glossary')
        ->sourceLang('en')
        ->targetLang('de')
        ->addEntry('artist', 'Künstler')
        ->addEntry('prize', 'Preis')
        ->create();

    echo "Created '{$glossaryInfo->name}' ({$glossaryInfo->glossaryId}) ";
    echo "{$glossaryInfo->sourceLang} to {$glossaryInfo->targetLang} ";
    echo "containing {$glossaryInfo->entryCount} entries\n";
} catch (\Exception $e) {
    echo "Error creating glossary: " . $e->getMessage();
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

try {
    $glossaryInfo = Deepl::createGlossaryBuilder()
        ->name('Extended Glossary')
        ->sourceLang('en')
        ->targetLang('de')
        ->addEntries([
            'hello' => 'hallo',
            'world' => 'welt',
            'goodbye' => 'auf Wiedersehen',
        ])
        ->create();

    echo "Created '{$glossaryInfo->name}' with ID {$glossaryInfo->glossaryId}";
} catch (\Exception $e) {
    echo "Error creating glossary: " . $e->getMessage();
}

use PavelZanek\LaravelDeepl\Facades\Deepl;
use DeepL\GlossaryEntries;

$entries = GlossaryEntries::fromEntries([
    'computer' => 'Computer',
    'internet' => 'Internet',
]);

try {
    $glossaryInfo = Deepl::createGlossaryBuilder()
        ->name('Tech Glossary')
        ->sourceLang('en')
        ->targetLang('de')
        ->addEntriesFromGlossaryEntries($entries)
        ->create();

    echo "Created '{$glossaryInfo->name}' with ID {$glossaryInfo->glossaryId}";
} catch (\Exception $e) {
    echo "Error creating glossary: " . $e->getMessage();
}

$csvData = file_get_contents('/path/to/glossary_file.csv');
$myCsvGlossary = $client->createGlossaryFromCsv('CSV glossary', 'en', 'de', $csvData);

use PavelZanek\LaravelDeepl\Facades\Deepl;

// Get source languages
$sourceLanguages = Deepl::getSourceLanguages();
foreach ($sourceLanguages as $sourceLanguage) {
    echo $sourceLanguage->name . ' (' . $sourceLanguage->code . ')';
    // Example: 'English (en)'
}

// Get target languages
$targetLanguages = Deepl::getTargetLanguages();
foreach ($targetLanguages as $targetLanguage) {
    $supportsFormality = $targetLanguage->supportsFormality ? 'supports formality' : 'does not support formality';
    echo $targetLanguage->name . ' (' . $targetLanguage->code . ') ' . $supportsFormality;
    // Example: 'German (de) supports formality'
}

// Get glossary-supported language pairs
$glossaryLanguages = Deepl::getGlossaryLanguages();
foreach ($glossaryLanguages as $glossaryLanguage) {
    echo $glossaryLanguage->sourceLang . ' to ' . $glossaryLanguage->targetLang;
    // Example: 'en to de'
}

use PavelZanek\LaravelDeepl\DeeplClient;

$client = app(DeeplClient::class);

// Get source languages
$sourceLanguages = $client->getSourceLanguages();
foreach ($sourceLanguages as $sourceLanguage) {
    echo $sourceLanguage->name . ' (' . $sourceLanguage->code . ')';
    // Example: 'English (en)'
}

// Get target languages
$targetLanguages = $client->getTargetLanguages();
foreach ($targetLanguages as $targetLanguage) {
    $supportsFormality = $targetLanguage->supportsFormality ? 'supports formality' : 'does not support formality';
    echo $targetLanguage->name . ' (' . $targetLanguage->code . ') ' . $supportsFormality;
    // Example: 'German (de) supports formality'
}

// Get glossary-supported language pairs
$glossaryLanguages = $client->getGlossaryLanguages();
foreach ($glossaryLanguages as $glossaryLanguage) {
    echo $glossaryLanguage->sourceLang . ' to ' . $glossaryLanguage->targetLang;
    // Example: 'en to de'
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

$languages = Deepl::languageBuilder()
    ->source()
    ->target()
    ->glossary()
    ->get();

// Accessing Source Languages
foreach ($languages['source_languages'] as $sourceLanguage) {
    echo $sourceLanguage->name . ' (' . $sourceLanguage->code . ")\n";
    // Example: 'English (en)'
}

echo "\n";

// Accessing Target Languages
foreach ($languages['target_languages'] as $targetLanguage) {
    $supportsFormality = $targetLanguage->supportsFormality ? 'supports formality' : 'does not support formality';
    echo $targetLanguage->name . ' (' . $targetLanguage->code . ') ' . $supportsFormality . "\n";
    // Example: 'German (de) supports formality'
}

echo "\n";

// Accessing Glossary-Supported Language Pairs
foreach ($languages['glossary_languages'] as $glossaryLanguage) {
    echo $glossaryLanguage->sourceLang . ' to ' . $glossaryLanguage->targetLang . "\n";
    // Example: 'en to de'
}

use PavelZanek\LaravelDeepl\Facades\Deepl;

$usage = Deepl::usage()->getUsage();



return [
    'welcome' => 'Welcome to our application!',
    'user' => [
        'profile' => 'Your profile',
        'settings' => 'Account settings',
    ],
    'greeting' => 'Hello, :name!',
];
  


return [
    'welcome' => 'Vítejte v naší aplikaci!',
    'user' => [
        'profile' => 'Váš profil',
        'settings' => 'Nastavení účtu',
    ],
    'greeting' => 'Ahoj, :name!',
];



return [
    'welcome' => 'Vítejte v naší aplikaci!',
    // The 'user' key is missing
    'greeting' => 'Ahoj, :name!',
];



return [
    'welcome' => 'Vítejte v naší aplikaci!',
    'user' => [
        'profile' => 'Váš profil',
        'settings' => 'Nastavení účtu',
    ],
    'greeting' => 'Ahoj, :name!',
];



namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Translation\Loader as LoaderContract;
use Illuminate\Translation\FileLoader;
use Illuminate\Filesystem\Filesystem;
use PavelZanek\LaravelDeepl\Services\TranslationService;
use PavelZanek\LaravelDeepl\Services\TranslatorService;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // Register this only if you intend to utilize the queue for handling translations
        $this->app->singleton(LoaderContract::class, function ($app) {
            return new FileLoader(new Filesystem(), lang_path());
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        $this->app->extend('translator', function ($translator, $app) {
            $loader = $app['translation.loader'];
            $translationService = $app->make(TranslationService::class);

            return new TranslatorService($loader, $app, $translationService);
        });
    }
}

'enable_on_the_fly_translation' => env('DEEPL_ENABLE_ON_THE_FLY_TRANSLATION', true),

'on_the_fly_outside_local' => env('DEEPL_ON_THE_FLY_OUTSIDE_LOCAL', false),

'on_the_fly_source_lang' => env('DEEPL_ON_THE_FLY_SOURCE_LANG', 'en'),

'on_the_fly_use_queue_for_translation' => env('DEEPL_ON_THE_FLY_USE_QUEUE_FOR_TRANSLATION', true),

use PavelZanek\LaravelDeepl\Facades\Deepl;
use PavelZanek\LaravelDeepl\Enums\V2\Formality;
use PavelZanek\LaravelDeepl\Enums\V2\SourceLanguage;
use PavelZanek\LaravelDeepl\Enums\V2\TargetLanguage;

$translatedText = Deepl::translateText()
    ->text('How are you today?')
    ->sourceLang(SourceLanguage::ENGLISH->value)
    ->targetLang(TargetLanguage::GERMAN->value)
    ->formality(Formality::PREFER_LESS->value)
    ->translate();

echo $translatedText; // Outputs: Wie geht es dir heute?
bash
php artisan vendor:publish --tag=laravel-deepl-config
bash
php artisan vendor:publish --tag=laravel-deepl-migrations
bash
php artisan migrate
bash
php artisan vendor:publish --tag=laravel-deepl-migrations
php artisan migrate
bash
php artisan deepl:usage
bash
php artisan deepl:translate {file} --sourceLang=en --targetLang=cs [--with-pint]
bash
php artisan deepl:translate lang/en/messages.php --sourceLang=en --targetLang=cs
bash
php artisan deepl:translate-folder {folder} --sourceLang=en --targetLang=cs [--with-pint]
bash
php artisan deepl:translate-folder lang/en --sourceLang=en --targetLang=cs
bash
php artisan deepl:translate-folder lang/en --sourceLang=en --targetLang=cs
bash
php artisan deepl:translate-folder resources/lang/en --sourceLang=en --targetLang=cs
bash
php artisan deepl:translate lang/en/messages.php --sourceLang=en --targetLang=cs