Laravel Localization · · 10 min read

mcamara/laravel-localization: A Practical Guide for Laravel 12

If you search for "laravel localization", one package dominates the results: mcamara/laravel-localization. It has been around since Laravel 4, it is still maintained, and it solves a problem Laravel leaves to you: putting the locale in the URL (/es/about, /de/about) and keeping the app, its links and its redirects consistent with it.

It's a good package. It also has a specific architecture, and that architecture explains every pitfall people hit with it. This guide covers what it does, how to install it on Laravel 12, where it bites, and when a 30-line middleware is the simpler answer.

What it actually does

Laravel's translator knows nothing about URLs. App::setLocale('es') changes which lang files __() reads, and that's all. Deciding the locale from the request, generating links that keep it, and redirecting people who arrive without one is your job.

The package does that job with a few parts:

  • A locale prefix for a route group. LaravelLocalization::setLocale() reads the first URL segment, sets the app locale if it is supported, and returns it so you can use it as the group prefix.
  • Redirect middleware that sends visitors without a locale in the URL to one, using the session, a cookie or the browser's Accept-Language header.
  • URL helpers such as getLocalizedURL() and localizeURL() for language switchers and links.
  • Translated routes, so /en/about and /es/acerca can point to the same controller.
  • A view-path middleware if you prefer resources/views/es/... folders over translation keys.

The one architectural fact to remember: setLocale() runs while your routes file loads, on every request. The package works out the locale from the current URL before routes exist and registers them under that prefix. Most of the gotchas below follow from this.

Installing it on Laravel 12

The current 2.x line requires PHP 8.2 and supports Laravel 11, 12 and 13.

composer require mcamara/laravel-localization
php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"

That creates config/laravellocalization.php. The keys you'll touch:

return [
    'supportedLocales' => [
        'en' => ['name' => 'English', 'script' => 'Latn', 'native' => 'English', 'regional' => 'en_GB'],
        'es' => ['name' => 'Spanish', 'script' => 'Latn', 'native' => 'español', 'regional' => 'es_ES'],
        'de' => ['name' => 'German',  'script' => 'Latn', 'native' => 'Deutsch', 'regional' => 'de_DE'],
    ],

    'useAcceptLanguageHeader' => true,
    'hideDefaultLocaleInURL' => false,
    'localesOrder' => [],
    'localesMapping' => [],
    'urlsIgnored' => ['/skipped'],
    'httpMethodsIgnored' => ['POST', 'PUT', 'PATCH', 'DELETE'],
];

Two things to know up front. First, the default locale is your app.locale, and the package throws an exception if that locale is not in supportedLocales. Second, the service provider does not register middleware aliases for you. On Laravel 12 you add them in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
        'localeCookieRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
        'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class,
    ]);
})

Then wrap your public routes:

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

Route::group([
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath'],
], function () {
    Route::get('/', HomeController::class)->name('home');
    Route::get('about', AboutController::class)->name('about');
});

// Routes that should not be localized go outside the group.

Only add localeViewPath if you actually keep views in per-locale folders. The README strongly recommends using a redirect middleware, and that advice is right. Without one, /about serves whatever language the visitor's browser asked for, which is bad for caching and for crawlers.

The middleware, precisely

The names don't explain much, so here is what each one does.

localeSessionRedirect: when the URL has a locale, it stores it in the session. When it doesn't, it redirects to the stored locale. If nothing is stored, and both hideDefaultLocaleInURL and useAcceptLanguageHeader are on, it negotiates from the browser first. It does not redirect to the default locale when that locale is hidden.

localeCookieRedirect: the same logic, using a cookie instead of the session.

localizationRedirect: when hideDefaultLocaleInURL is true and the URL contains the default locale, it redirects /en/about to /about.

localize: only needed for translated routes. It works out which translated route the current path matches, so URL helpers can translate it to another locale.

All of them skip the methods in httpMethodsIgnored and the paths in urlsIgnored. That's why POST requests aren't redirected by default: a redirect would turn the POST into a GET.

Language switchers and links

The package's switcher example is worth copying as-is:

<ul>
    @foreach (LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a hreflang="{{ $localeCode }}"
               href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endforeach
</ul>

The fourth argument, forceDefaultLocation, matters when the default locale is hidden. Say a visitor has Spanish stored in their session and clicks "English". A link to /about hits localeSessionRedirect, which sees Spanish in the session and sends them back to /es/about. They can never switch. Forcing /en/about instead lets the session middleware store en, and then localizationRedirect takes them to /about.

For ordinary links and form actions, use LaravelLocalization::localizeURL('/about'), or named routes generated inside the localized group. An unlocalized form action like /logout gets redirected and can show up as a MethodNotAllowedHttpException, or as validation messages in the wrong language. The README lists all three symptoms under the same cause.

Translated routes

To get /en/about and /es/acerca, add a routes.php file to each locale in lang/:

// lang/es/routes.php
return [
    'about' => 'acerca',
    'article' => 'articulo/{article}',
];

Register the routes with transRoute() inside a group that includes localize:

Route::group([
    'prefix' => LaravelLocalization::setLocale(),
    'middleware' => ['localize', 'localeSessionRedirect', 'localizationRedirect'],
], function () {
    Route::get(LaravelLocalization::transRoute('routes.about'), AboutController::class);
    Route::get(LaravelLocalization::transRoute('routes.article'), ShowArticleController::class);
});

getURLFromRouteNameTranslated('es', 'routes.about') returns /es/acerca. For translated slugs in parameters (/es/articulo/cambio-importante), your model implements Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable with a getLocalizedRouteKey($locale) method, and you override resolveRouteBinding() to find the record by the localized slug.

Pitfall 1: route caching returns 404s

This catches people on their first deploy. The package's own README says plainly that it isn't compatible with Laravel's route cache by default: php artisan route:cache, or php artisan optimize, which many deploy scripts run, will make localized routes return 404.

The reason is the architecture above. A cached route file is built once, in the console, with no URL, so only one prefix ever gets registered. The fix is to cache one route file per locale. On Laravel 11 and 12, add the package's trait to AppServiceProvider:

use Illuminate\Foundation\Support\Providers\RouteServiceProvider;
use Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes;

class AppServiceProvider extends ServiceProvider
{
    use LoadsTranslatedCachedRoutes;

    public function boot(): void
    {
        RouteServiceProvider::loadCachedRoutesUsing(fn () => $this->loadCachedRoutes());
    }
}

Then replace route:cache in your deploy with php artisan route:trans:cache, and use route:trans:clear and route:trans:list es to inspect it. If your deploy runs optimize, swap it for the individual cache commands, or optimize will overwrite the per-locale cache with one that's broken.

Tests have a related quirk: the app boots before the test request exists, so the prefix is empty and localized routes 404. The README shows a refreshApplicationWithLocale() helper for Pest and PHPUnit that sets the LaravelLocalization::ENV_ROUTE_KEY environment variable before booting.

Pitfall 2: Livewire and AJAX requests

Livewire sends component updates as a POST to /livewire/update. That URL has no locale segment, so when your routes file runs setLocale(), it finds no supported locale and falls back to the default, or to Accept-Language if the default isn't hidden. A component on /es/pricing renders its first load in Spanish and its first update in English.

One way to fix it is to register Livewire's update route inside the localized group, so the endpoint carries the prefix:

use Livewire\Livewire;

Route::group(['prefix' => LaravelLocalization::setLocale()], function () {
    Livewire::setUpdateRoute(fn ($handle) => Route::post('livewire/update', $handle));

    // ...localized routes
});

On /es/pricing, Livewire then posts to /es/livewire/update, and setLocale() picks up es. Test this against your own setup. The same reasoning applies to any fetch or API call your pages make: if the URL has no locale, the request runs in the default one. The Livewire translations post covers the component side, and the API localization post covers requests that never had a URL prefix to begin with.

Pitfall 3: duplicate default-locale URLs

There are two settings and two outcomes, and only one combination is clean:

  • hideDefaultLocaleInURL => false with localeSessionRedirect: /about redirects to /en/about. One URL per page per language.
  • hideDefaultLocaleInURL => true with localizationRedirect: /en/about redirects to /about. Also one URL per page per language.
  • hideDefaultLocaleInURL => true without localizationRedirect: /about and /en/about both return 200 with identical content.

The package's config comments warn about the third case. Also note that these redirects are 302s with Vary: Accept-Language, not permanent redirects. That's deliberate, since the destination depends on the visitor. But it means the unprefixed URL never consolidates into the prefixed one, so make sure your sitemap, canonicals and internal links only ever point at the final URL.

Pitfall 4: it doesn't output hreflang

The switcher markup above puts hreflang on <a> tags, which helps users but isn't how search engines discover alternates. You need <link rel="alternate"> tags in the <head>, and the package leaves that to you:

@php($path = url()->current())

@foreach (LaravelLocalization::getSupportedLocales() as $code => $properties)
    <link rel="alternate" hreflang="{{ $code }}" href="{{ LaravelLocalization::getLocalizedURL($code, $path) }}">
@endforeach

<link rel="alternate" hreflang="x-default" href="{{ LaravelLocalization::getLocalizedURL(config('app.locale'), $path) }}">

Two details matter here. Don't pass forceDefaultLocation in this case, because /en/about would be a URL that redirects, and alternates should point at final URLs. And pass url()->current() rather than relying on the default: with no URL argument, getLocalizedURL() uses the full current URL, query string included, so ?utm_source=... would leak into every alternate. Locale keys also need to be valid BCP 47 tags (de-AT, not de_AT) if you use them directly. The full picture, including return links, is in the multilingual SEO and hreflang guide.

When a hand-rolled middleware is simpler

The package is worth it if you need translated route segments, browser-based redirects, or a ready-made set of helpers. If all you need is /{locale}/..., Laravel can do that with static routes that cache normally:

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

Route::redirect('/', '/en', 301);
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;

class SetLocaleFromUrl
{
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->route('locale');

        App::setLocale($locale);
        URL::defaults(['locale' => $locale]);

        // Keep controller signatures free of the locale parameter.
        $request->route()->forgetParameter('locale');

        return $next($request);
    }
}

URL::defaults() means route('about') produces /es/about without passing the locale everywhere. Register the middleware with Livewire::addPersistentMiddleware() and Livewire re-runs it against the original page's route on every component update. You give up translated slugs and automatic browser redirects. You keep route:cache, plain routing and nothing to configure. For a SaaS with a marketing site in a few languages and an app behind login, that trade is often worth making. If you have tenants with their own locale rules, the multi-tenant localization post covers that layer.

If you're starting fresh and want the package's feature set, its README now points to a successor, niels-numbers/laravel-localizer, which registers routes statically and supports route:cache natively. mcamara/laravel-localization is still maintained for existing users, and there is a migration guide between the two.

Routing is only half of it

Whichever option you choose, it decides which locale a request runs in. It doesn't decide whether the strings in that locale exist, are current, or fall back quietly to the fallback locale. Those are separate problems. LangSyncer handles the second one: it manages the translation strings themselves, shows what's missing per language, and lets non-developers fix copy live without a deploy, while your router, package or hand-rolled, keeps handling URLs. For language-specific details like plural rules and formatting, the Laravel localization guides go through each language.

More on Laravel Localization

All Laravel Localization articles →

We'd like to use analytics and marketing cookies to understand how the site is used. They stay off unless you accept them. Cookie Policy