Setup

Add your key to .env and expose it through config/services.php:

php
// .env
GLOSSFERRY_API_KEY=gf_live_xxxxxxxx

// config/services.php
'glossferry' => [
    'key' => env('GLOSSFERRY_API_KEY'),
],

The command

Create it with php artisan make:command TranslateLang and replace the contents with the code below. Run it with php artisan lang:translate DE.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;

class TranslateLang extends Command
{
    protected $signature = 'lang:translate {target : Target language code, for example DE}';
    protected $description = 'Translate lang/en files with the Glossferry API';

    public function handle(): int
    {
        $target = strtoupper($this->argument('target'));
        $locale = strtolower($target);

        foreach (glob(lang_path('en/*.php')) as $path) {
            $name = basename($path);
            $flat = array_map('strval', Arr::dot(require $path));
            $out = [];

            foreach ($this->batches($flat) as $batch) {
                $response = Http::withToken(config('services.glossferry.key'))
                    ->post('https://api.glossferry.com/v1/translate', [
                        'text' => array_values($batch),
                        'target_lang' => $target,
                        'source_lang' => 'EN',
                    ])
                    ->throw()
                    ->json();

                foreach (array_keys($batch) as $i => $key) {
                    $translated = $response['translations'][$i]['text'];
                    if ($this->placeholders($batch[$key]) !== $this->placeholders($translated)) {
                        $this->warn("Placeholder mismatch, kept source text: {$name} {$key}");
                        $translated = $batch[$key];
                    }
                    Arr::set($out, $key, $translated);
                }
            }

            File::ensureDirectoryExists(lang_path($locale));
            File::put(lang_path("{$locale}/{$name}"), "<?php\n\nreturn ".var_export($out, true).";\n");
            $this->info("Wrote lang/{$locale}/{$name}");
        }

        return self::SUCCESS;
    }

    /** Split into batches of at most 50 strings and 40,000 characters. */
    private function batches(array $flat): array
    {
        $batches = [];
        $current = [];
        $chars = 0;

        foreach ($flat as $key => $value) {
            $length = mb_strlen($value);
            if ($current && (count($current) >= 50 || $chars + $length > 40000)) {
                $batches[] = $current;
                $current = [];
                $chars = 0;
            }
            $current[$key] = $value;
            $chars += $length;
        }

        if ($current) {
            $batches[] = $current;
        }

        return $batches;
    }

    /** Laravel :placeholders and printf-style tokens, as a sorted list for comparison. */
    private function placeholders(string $text): string
    {
        preg_match_all('/:[A-Za-z_][A-Za-z0-9_]*|%[sd]|\{[^}]+\}/', $text, $matches);
        $tokens = $matches[0];
        sort($tokens);

        return implode('|', $tokens);
    }
}

Notes

  • Pluralisation. Strings like "one item|:count items" contain a pipe. Check the result for those keys and fix them by hand if the pipes or counts changed.
  • JSON language files. For lang/en.json use the same approach with json_decode and json_encode, or the Node script in the JSON guide.
  • Existing translations. This version overwrites the target files. Skip keys that already exist if you maintain translations by hand.
  • Cost. 90,000 characters cost EUR 1.08 per language at EUR 12.00 per million.