+1 (415) 599-8902

Localizing a Laravel App: Translations, Locale Routing, Pluralization and Formatting

Shipping to more than one market means more than swapping strings. This tutorial builds a small, robust localization setup in a recent Laravel application: translation files, per-request locale detection, locale-prefixed routes, pluralization, locale-aware formatting, and a test that catches missing keys.

Publish the language files

Recent Laravel skeletons do not ship a lang directory. Publish it, then add your locales:

php artisan lang:publish
mkdir lang/pl lang/de

Set defaults in .env:

APP_LOCALE=en
APP_FALLBACK_LOCALE=en

Organize translations

Use PHP files for structured keys and JSON files for short sentences that double as keys.

// lang/en/dashboard.php
return [
    'welcome' => 'Welcome back, :name',
    'projects' => '{0} No projects|{1} One project|[2,*] :count projects',
];
// lang/pl/dashboard.php
return [
    'welcome' => 'Witaj ponownie, :name',
    'projects' => '{0} Brak projektów|{1} Jeden projekt|[2,*] :count projektów',
];

Use them in Blade or PHP:

<h1>{{ __('dashboard.welcome', ['name' => $user->name]) }}</h1>
<p>{{ trans_choice('dashboard.projects', $count) }}</p>

Polish has several plural forms (one, few, many, other). Laravel's pipe syntax supports explicit ranges, so you can spell them out when needed:

'files' => '{1} :count plik|[2,4] :count pliki|[5,*] :count plików',

Note that this simple range form is an approximation for languages with complex rules (for example 22 files is "few" in Polish). For production, verify your rules with a native speaker and add cases as needed.

Locale-prefixed routes

Putting the locale in the URL (/pl/pricing) is good for SEO and shareable links.

// routes/web.php
Route::prefix('{locale}')
    ->where(['locale' => 'en|pl|de'])
    ->middleware('set.locale')
    ->group(function () {
        Route::get('/', HomeController::class)->name('home');
        Route::get('/pricing', PricingController::class)->name('pricing');
    });

Route::get('/', fn () => redirect('/'.config('app.locale')));

Set a default so route('pricing') does not need the locale every time:

// app/Http/Middleware/SetLocale.php
class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        $locale = $request->route('locale');

        app()->setLocale($locale);
        URL::defaults(['locale' => $locale]);
        $request->route()->forgetParameter('locale');

        return $next($request);
    }
}

Register the alias in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias(['set.locale' => \App\Http\Middleware\SetLocale::class]);
})

Forgetting the route parameter keeps controller signatures clean, so they do not need a $locale argument.

Detect a first-visit locale

For the root redirect, use the browser's preference but only among supported locales:

Route::get('/', function (Request $request) {
    $locale = $request->getPreferredLanguage(['en', 'pl', 'de']) ?? 'en';
    return redirect('/'.$locale);
});

If a user is logged in, store their choice in a locale column and prefer that over the header.

Queues, mail and notifications

The locale is per-request, so queued work would otherwise fall back to the default. Mailables and notifications can carry a locale:

Mail::to($user)->locale($user->locale)->send(new InvoicePaid($invoice));
$user->notify((new InvoicePaid($invoice))->locale($user->locale));

For your own jobs, pass the locale in and wrap the work in App::withLocale($locale, fn () => ...).

Format dates, numbers and money

Translating text is not enough; formats differ too. Carbon respects the app locale for human-readable output:

$invoice->created_at->translatedFormat('j F Y');
$invoice->created_at->diffForHumans();

For currency, use PHP's intl extension rather than hand-built strings:

$fmt = new NumberFormatter(app()->getLocale(), NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234.5, 'EUR');

Laravel's Number helper also offers locale-aware formatting:

use Illuminate\Support\Number;

Number::currency(1234.5, in: 'EUR', locale: 'pl');
Number::format(1234567.89, locale: 'de');

Translatable database content

UI strings live in language files, but user-facing records (product names, articles) belong in the database. Two common approaches are a JSON column per attribute (a package such as spatie/laravel-translatable wraps this) or a separate translations table. JSON columns are simpler; a translations table is better when you need to query or index by translated values.

Test for missing keys

A missing key silently renders as the key itself. Catch it in CI by comparing locale files to the default:

it('has every english key in every locale', function (string $locale) {
    $base = collect(Arr::dot(require lang_path('en/dashboard.php')))->keys();
    $other = collect(Arr::dot(require lang_path("$locale/dashboard.php")))->keys();

    expect($base->diff($other)->values()->all())->toBe([]);
})->with(['pl', 'de']);

Also add a feature test that hits /pl and asserts a translated string appears, so routing and middleware stay covered.

it('renders the polish home page', function () {
    $this->get('/pl')->assertOk()->assertSee('Witaj');
});

Checklist

  • Locales whitelisted in routes, middleware and validation.
  • hreflang links in the page head for each language version.
  • Queued mail and notifications carry the user's locale.
  • Dates, numbers and currency use locale-aware formatters.
  • CI fails when a locale is missing keys.

Need help internationalizing an existing Laravel application? Get in touch and tell us about your project.