Localization
Localization gives a Laravel application two ways to pick the language of a response. Path mode puts the locale in the URL (/products, /ar/products, /fr/produits) with static, cacheable routes, which suits public websites and SEO. Negotiated mode keeps the URL unchanged and picks the locale from an ordered list of sources such as the authenticated user or the Accept-Language header, which suits APIs.
Static Localized Routes
One real route per locale, registered once, safe for route:cache.
Translated URLs
Translate URL segments with ordinary lang files, Unicode included.
Resolver Pipeline
User, session, cookie, header or your own resolver, in the order you choose.
Laravel Is the Source
The default comes from app.locale and translation fallback stays with Laravel.
Alternates and hreflang
Language switcher links and hreflang tags for the current page.
No Hidden State
No automatic redirects, no automatic persistence, nothing kept between requests.
An explicit locale in the URL always wins. /ar/products is Arabic whatever the user's cookie, session or browser prefers, and /products is always the default language.
#When not to use it
You don't need this package when your application only translates strings with Laravel's __() and has no localized URLs, or when an API only needs a three-line middleware that calls App::setLocale() from one header.
#Installation
Install the package with Composer. The service provider, the Route::localized() macro, the localization middleware alias and the locale() helper are registered automatically.
#Requirements
- PHP 8.2, 8.3, 8.4 or 8.5
- Laravel 12.x (12.0 or later)
ext-intl: it provides locale display names forname()andnativeName()
#Composer Installation
composer require pharaonic/laravel-localization#Publish Configuration
Publish the configuration file to config/pharaonic/localization.php:
php artisan vendor:publish --tag=localization-configThen list your locales. The default locale is Laravel's app.locale and must be one of them:
1'supported' => ['en', 'ar', 'fr'],#Check the Setup
php artisan localization:doctorYou're all set! Wrap routes in Route::localized() for localized URLs, or add the localization middleware to API routes.
The package ships no migrations and needs no session or cookie middleware for path routes or header-only APIs. Session and cookie resolvers only read what your own middleware already provides.
#Concepts
The package keeps a few ideas apart that are easy to mix up.
| Concept | Meaning | Where it comes from |
|---|---|---|
| Default locale | The locale of unprefixed URLs, and of negotiation when no source matches | Laravel's app.locale |
| Translation fallback | The locale Laravel's translator uses for a missing string | Laravel's app.fallback_locale |
| Supported locales | The locales routes are registered for and negotiation may pick | localization.supported |
| Mode | path (the URL carries the locale) or negotiated (it doesn't) | Route::localized() or the localization middleware |
| Resolver | One source of a locale preference: user, session, cookie, header or a class | localization.resolvers |
| Source | Which resolver decided the current request, or path / default | locale()->source() |
#Path mode
Route::localized() registers each route once per supported locale when your routes file loads. The route itself carries its locale, so the request never decides which routes exist and nothing is redirected based on preferences.
1/products → en (default, hidden prefix)2/ar/المنتجات → ar3/fr/produits → fr4/en/products → 301 to /products5/de/products → 404 (de is not supported)#Negotiated mode
The localization middleware runs a resolver profile in order. The first supported result wins; otherwise the default locale is used. The URL never changes and nothing is redirected.
1user preferredLocale() → null, try next2Accept-Language: ar-EG,ar;q=0.9 → ar, stop#What is never done automatically
- No redirect based on a cookie, session, user or header.
- No write to the session, a cookie or the user when a locale is resolved.
- No change to
config('app.fallback_locale'), and no fallback locale used as a negotiation source. - No override of
route(),url()orURL::defaults().
Laravel's App::setLocale() writes config('app.locale'). The package applies locales with App::setLocale() so app()->getLocale(), validation messages and Carbon follow the request, reads the default locale once when the application boots, and restores the previous locale when the request ends.
#Configuration
The configuration lives in config/pharaonic/localization.php. It holds only strings, booleans and arrays, so it works with config:cache. Every value is validated the first time the package needs it, with an exception that names the wrong key.
1return [ 2 'supported' => ['en', 'ar', 'fr'], 3 4 'path' => [ 5 'hide_default' => true, 6 'canonical_redirect' => true, 7 'prefixes' => [], 8 ], 9 10 'resolvers' => [11 'web' => ['user', 'session', 'cookie', 'header'],12 'api' => ['user', 'header'],13 ],14 15 'session' => ['key' => 'locale'],16 17 'cookie' => [18 'key' => 'locale',19 'minutes' => 60 * 24 * 365,20 'same_site' => 'lax',21 'secure' => null,22 ],23 24 'header' => ['name' => 'Accept-Language'],25 26 'locales' => [],27];#Options
| Key | Default | Description |
|---|---|---|
supported | null | List of locale codes. null supports only app.locale. Must contain app.locale exactly as written there. |
path.hide_default | true | The default locale lives at unprefixed URLs. With false, every locale has a prefix and /products is a 404. |
path.canonical_redirect | true | With hide_default, GET/HEAD /{default}/... redirects (301) to the unprefixed URL. With false, it is a 404. |
path.prefixes | [] | URL prefix overrides, e.g. ['pt_BR' => 'br']. By default the prefix is the lowercase BCP 47 tag (pt-br). |
resolvers | web, api | Named profiles: ordered lists of user, session, cookie, header or a resolver class name. |
session.key | locale | Session key read by the session resolver and written by remember(). |
cookie.key | locale | Cookie name read by the cookie resolver and written by remember(). |
cookie.minutes | one year | Lifetime of a remembered cookie. |
cookie.same_site | lax | lax, strict, none or null. |
cookie.secure | null | null uses Laravel's session.secure. |
header.name | Accept-Language | Header read by the header resolver. |
locales | [] | Optional metadata per locale: name, native, direction (ltr or rtl), and any custom key. |
Set the default locale with app.locale in config/app.php and the translation fallback with app.fallback_locale. The package reads both from Laravel and never duplicates them.
#Locale codes
Codes are matched without regard to case or -/_, but the package always returns the exact code you configured. pt_BR, pt-br and PT-BR are the same locale, so listing two of them is an error, and so are two locales with the same URL prefix.
#Metadata
locale()->name() and nativeName() use the locales entry, then ext-intl (ICU), then the code itself when ICU has no name for it. direction() uses the locales entry, then the script (uz_Arab is RTL), then the language (ar, fa, he, ur and other RTL languages). The region never decides the direction.
1'locales' => [2 'ar' => ['name' => 'Arabic', 'native' => 'العربية'],3 'ku' => ['direction' => 'rtl'],4],#Custom metadata
Any other key in a locales entry is kept as it is: a flag path or URL, an emoji, a currency, a date format, or a nested array. locale()->meta() reads one value with dot notation, for the current locale or the one given, and returns the default when the key is missing. locale()->metadata() returns the resolved name, native and direction with every custom key, for example to pass to a frontend.
1'locales' => [2 'ar' => ['flag' => ['emoji' => '🇪🇬', 'url' => '/flags/eg.svg'], 'currency' => 'EGP'],3 'en' => ['flag' => ['emoji' => '🇬🇧', 'url' => '/flags/gb.svg'], 'currency' => 'USD'],4],1locale()->meta('currency'); // "EGP" while the locale is ar2locale()->meta('flag.url', locale: 'en'); // "/flags/gb.svg"3locale()->meta('flag', null, 'fr'); // null: fr has no flag4locale()->metadata('ar');5// ["name" => "Arabic", "native" => "العربية", "direction" => "rtl", "flag" => [...], "currency" => "EGP"]Values must be plain data (strings, numbers, booleans, arrays) so config:cache can store them. A locale code may appear only once in locales, in any spelling.
#Path Routing
Wrap the routes that should exist in every language in Route::localized(). Inside it, you write ordinary Laravel routes.
1use App\Http\Controllers\ProductController;2use Illuminate\Support\Facades\Route;3 4Route::localized(function (): void {5 Route::get('/', [ProductController::class, 'home'])->name('home');6 Route::get('/products', [ProductController::class, 'index'])->name('products.index');7 Route::get('/products/{product}', [ProductController::class, 'show'])->name('products.show');8});With supported set to ['en', 'ar', 'fr'] and app.locale set to en, this registers:
| URI | Name | Locale |
|---|---|---|
/products | products.index | en |
/ar/products | localized.ar.products.index | ar |
/fr/products | localized.fr.products.index | fr |
/en/products (GET, HEAD) | localized.redirect.products.index | 301 to /products |
Each route runs the SetPathLocale middleware, which applies its locale, sets Content-Language, and restores the previous locale when the request ends.
#Route names
- The default-locale route keeps your name, so
route('products.index')still works and returns the default-locale URL. - Other locales use the reserved
localized.{locale}.{name}namespace. Uselocale()->route()rather than these names. - An unnamed route gets a deterministic name,
localized.{locale}.uri.{hash}, so the language switcher still works for it. - A route name starting with
localized.insideRoute::localized()is rejected.
#Groups, resources and constraints
Everything Laravel groups provide keeps working: prefixes, name prefixes, middleware, domains, where constraints, optional parameters, resources and controller groups. Outer prefixes come before the locale prefix.
1use App\Http\Controllers\ProductController; 2 3Route::middleware('web')->prefix('shop')->name('shop.')->group(function (): void { 4 Route::localized(function (): void { 5 Route::resource('products', ProductController::class)->only(['index', 'show']); 6 }); 7}); 8 9// /shop/products shop.products.index10// /shop/ar/products localized.ar.shop.products.index#The default locale
With path.hide_default set to true (the default), the default locale lives at unprefixed URLs. /products is always served in the default locale, even when the user, session, cookie or browser prefers another language. With false, every locale has a prefix (/en/products), and /products doesn't exist.
#Canonical redirects
With hide_default and path.canonical_redirect (both on by default), GET and HEAD requests to /en/... redirect with 301 to the unprefixed URL, keeping the path parameters and the query string as they were sent. Other methods get Laravel's normal 404 or 405, never a redirect. With canonical_redirect set to false, /en/... is a 404.
Browsers and search engines keep a 301. If you later turn hide_default off, /en/... becomes the real URL while some clients still redirect it to /..., which then no longer exists. Plan URL policy changes, and test them with a cleared browser cache.
#Unsupported prefixes
There is no catch-all. /de/products is simply not a registered route, so it is a 404 (or whatever route your application registers at that URI), and it is never redirected or guessed. Collisions are detected when routes are registered: a localized URI that is already taken, two locales translating to the same URI, or a name already in use throw an InvalidLocalizationConfigurationException.
#Route caching
The routes are static, so php artisan route:cache works, with the locale stored in each route's action. Use controller or invokable actions: Laravel cannot cache closure routes. After changing supported or prefixes, run route:cache again; localization:doctor reports a stale cache.
php artisan route:cachephp artisan route:list --name=localized.arPrefixed locales are registered before the default one, so an unprefixed /{page} route can never capture /ar.
#Translated Routes
Translate the static segments of localized URIs with a routes.php lang file per locale, in lang/ (or resources/lang/ in applications upgraded from Laravel 8). Each key is one URI segment, each value its translation.
1return [2 'products' => 'المنتجات',3 'about' => 'من-نحن',4];1return [2 'products' => 'produits',3 'about' => 'a-propos',4]; 1use App\Http\Controllers\AboutController; 2use App\Http\Controllers\ProductController; 3 4Route::localized(function (): void { 5 Route::get('/products/{product}', [ProductController::class, 'show'])->name('products.show'); 6 Route::get('/about', AboutController::class)->name('about'); 7}); 8 9// /products/{product} /about10// /ar/المنتجات/{product} /ar/من-نحن11// /fr/produits/{product} /fr/a-propos#Rules
- Only static segments are translated. Placeholders (
{product},{page?}), their constraints and their order never change. - Segments come from inside
Route::localized(): an outer group prefix such asshopis not translated. - A missing translation keeps the original segment. The translator's fallback locale is never used for URLs.
- A translation must be one segment: no
/,{,},?,#,%or spaces. Anything else throws when routes are registered. - Translations are read when routes are registered, so a cached route file needs no lang lookups. Clear and rebuild the route cache after changing them.
#Unicode
Unicode segments are matched by Laravel and percent-encoded once in generated URLs:
1locale()->route('products.show', ['product' => 5], 'ar');2// "https://example.com/ar/%D8%A7%D9%84%D9%85%D9%86%D8%AA%D8%AC%D8%A7%D8%AA/5"#Localized URLs
locale()->route() builds the URL of a localized route in any locale, through Laravel's URL generator and the concrete route name. It never changes the current locale or a registered route.
1locale()->route('products.index'); // current locale2locale()->route('products.index', locale: 'ar'); // "https://example.com/ar/products"3locale()->route('products.show', ['product' => 5], 'fr'); // "https://example.com/fr/products/5"4locale()->route('products.show', 5, 'fr', false); // "/fr/products/5"The signature is route(string $name, mixed $parameters = [], ?string $locale = null, bool $absolute = true). Parameters work as with route(): arrays, a single value, models, extra keys as the query string.
#Errors
| Situation | Exception |
|---|---|
The route doesn't exist, or wasn't registered inside Route::localized() | LocalizedRouteNotFoundException (a Symfony RouteNotFoundException) |
The locale isn't supported (de, or ar-EG when only ar is) | UnsupportedLocaleException |
A HasLocalizedRouteKey parameter has no key in that locale | MissingLocalizedRouteKeyException |
All three live in Pharaonic\Laravel\Localization\Exceptions.
#The current locale
1locale()->current(); // "ar", the active App::getLocale()2locale()->default(); // "en", app.locale3locale()->source(); // "path", "user", "session", "cookie", "header", a class name, "default", or null4locale()->mode(); // "path", "negotiated", or null outside a localized request5locale()->supported(); // ["en", "ar", "fr"]#Matching and normalizing
1locale()->isSupported('AR'); // true (case and -/_ insensitive, no fallback)2locale()->isSupported('ar-EG'); // false3locale()->match('ar-EG'); // "ar" (exact, then parent, then first configured variant)4locale()->match('pt'); // "pt_BR" when pt_BR is the first configured pt locale5locale()->normalize('pt_br'); // "pt-BR" (BCP 47)normalize() throws an InvalidArgumentException for a malformed code; match() returns null.
#Metadata
1locale()->name('ar'); // "Arabic"2locale()->nativeName('ar'); // "العربية"3locale()->direction(); // "rtl" for the current locale4locale()->isRTL('fr'); // false1<html lang="{{ locale()->normalize(locale()->current()) }}" dir="{{ locale()->direction() }}">#Localized Model Binding
A model can have a different route key in each locale, such as a translated slug, by implementing HasLocalizedRouteKey. No trait, column or database schema is required.
1use Illuminate\Database\Eloquent\Model; 2use Pharaonic\Laravel\Localization\Contracts\HasLocalizedRouteKey; 3 4class Post extends Model implements HasLocalizedRouteKey 5{ 6 protected $casts = ['slugs' => 'array']; 7 8 public function getLocalizedRouteKey(string $locale): ?string 9 {10 return $this->slugs[$locale] ?? null;11 }12 13 public function resolveRouteBinding($value, $field = null)14 {15 return $this->where('slugs->'.app()->getLocale(), $value)->first();16 }17}#Generating URLs
locale()->route(), switchUrl(), alternates() and the signed-route methods use getLocalizedRouteKey($locale) for every parameter that implements the contract.
1locale()->route('posts.show', $post, 'en'); // "https://example.com/posts/clean-architecture"2locale()->route('posts.show', $post, 'ar'); // "https://example.com/ar/posts/معمارية-البرمجيات" (encoded)When the model has no key in a locale, route() throws MissingLocalizedRouteKeyException instead of building a wrong-language URL, and switchUrl(), alternates() and hreflangs() leave that locale out.
#Resolving incoming URLs
Your model resolves the incoming value, as with any Laravel binding: in resolveRouteBinding() read app()->getLocale(), which already holds the URL locale. The package places its middleware right before SubstituteBindings in Laravel's middleware priority, so the locale is set before bindings run (and after the session and authentication middleware). A slug from another locale, such as the English slug under /ar/..., finds nothing and is a 404.
The package only sets the locale before binding. A model's getRouteKeyName() and numeric IDs keep Laravel's behavior; a model that doesn't implement the contract is generated with its normal route key. Packages such as spatie/laravel-translatable can back getLocalizedRouteKey(), but no integration is built in.
#SEO and Language Switching
On a path-localized page, the package builds the URL of the same page in each locale from the current route and its parameters.
#Language switcher
switchUrl() keeps the route parameters and the query string. It returns null when the page can't be built in that locale: the route isn't localized, a model has no localized key, or the URL is signed.
1<nav aria-label="Language"> 2 @foreach (locale()->supported() as $code) 3 @if ($url = locale()->switchUrl($code)) 4 <a href="{{ $url }}" hreflang="{{ locale()->normalize($code) }}" lang="{{ locale()->normalize($code) }}" 5 @if ($code === locale()->current()) aria-current="true" @endif> 6 @if ($flag = locale()->meta('flag', locale: $code)) 7 <img src="{{ $flag }}" alt="" width="20" height="14"> 8 @endif 9 {{ locale()->nativeName($code) }}10 </a>11 @endif12 @endforeach13</nav>flag is a custom metadata key you set in locales, e.g. 'ar' => ['flag' => '/flags/eg.svg']; the package ships no flags.
Switching only builds a link. It doesn't store the choice; see Locale Preferences for remembering it.
#Alternates and hreflang
alternates() returns locale => absolute URL for each locale the page exists in, without the query string. hreflangs() returns the same URLs keyed by BCP 47 tag, plus x-default pointing at the default-locale URL.
1locale()->alternates();2// ["en" => "https://example.com/posts/hello", "ar" => "https://example.com/ar/posts/..."]3 4locale()->hreflangs();5// ["en" => "...", "ar" => "...", "pt-BR" => "...", "x-default" => "https://example.com/posts/hello"]Both return an empty array outside path-localized routes (including negotiated API responses) and on signed URLs.
1<head>2 <link rel="canonical" href="{{ locale()->alternates()[locale()->current()] ?? url()->current() }}">3 @foreach (locale()->hreflangs() as $hreflang => $url)4 <link rel="alternate" hreflang="{{ $hreflang }}" href="{{ $url }}">5 @endforeach6</head>Blade's {{ }} escapes every value. Nothing is added to your views automatically.
#With Pharaonic SEO
When your application uses pharaonic/laravel-seo, hand the links to its alternates element instead, so they render once with the rest of @seo. Localization doesn't depend on it.
1foreach (locale()->hreflangs() as $hreflang => $url) {2 seo()->alternates->add($hreflang, $url);3}This snippet uses laravel-seo's seo()->alternates->add() API; the package doesn't ship or test an automatic integration. Add the links in one place only, so they aren't printed twice.
#Negotiated Localization
For APIs and personalized responses, add the localization middleware. The URL stays the same, and the locale comes from a resolver profile.
1use App\Http\Controllers\ApiProductController;2 3Route::middleware('localization')->group(function (): void {4 Route::get('/products', [ApiProductController::class, 'index']);5});The argument is the profile name: localization uses api, localization:web uses web.
1GET /api/products2Accept-Language: ar-EG,ar;q=0.9,en;q=0.834→ Content-Language: ar, Vary: Accept-Language, locale()->source() === "header"#The pipeline
Resolvers run in the configured order; the first one returning a supported locale wins.
1'resolvers' => [2 'web' => ['user', 'session', 'cookie', 'header'],3 'api' => ['user', 'header'],4],null, blank, malformed and unsupported values fall through to the next resolver, so a stale cookie never breaks a request. Each value is matched likelocale()->match(), soar_EGfrom a user becomesar.- Without a match, the locale is
app.localeand the sourcedefault.app.fallback_localeis never used: it remains Laravel's fallback for missing translation strings. - An exception thrown by a resolver is not caught, so a broken resolver fails visibly.
#Built-in resolvers
| ID | Reads | Notes |
|---|---|---|
user | $request->user()->preferredLocale() | When the user implements Laravel's HasLocalePreference. No trait or column is required. |
session | session.key | Only when the session is already started (the web group). Never starts one. |
cookie | cookie.key | As the request carries it: decrypted by EncryptCookies in the web group. Never writes one. |
header | Accept-Language (or header.name) | Quality values, q=0, *, language-range matching; malformed entries are skipped and parsing is bounded. |
1use Illuminate\Contracts\Translation\HasLocalePreference;2 3class User extends Authenticatable implements HasLocalePreference4{5 public function preferredLocale(): ?string6 {7 return $this->locale;8 }9}#Middleware order
The package puts localization after authentication in Laravel's middleware priority, so the user resolver sees token users whatever order you list them in:
1use App\Http\Controllers\MeController;2 3Route::middleware(['auth:sanctum', 'localization'])->get('/me', MeController::class);For session and cookie, the route needs the web group (or StartSession and EncryptCookies); localization:doctor warns when they are missing.
#Response headers
Content-Languageis set to the BCP 47 tag of the locale, unless the response already has one.- When the
headerresolver ran, the header name is added toVary, keeping existing values. - When the
user,sessionorcookieresolver ran, a response markedpublicor withs-maxageis madeprivate, so a shared cache can't serve one user's language to another.no-storeresponses and Laravel's defaultno-cache, privateare left alone.
A Vary: Accept-Language response is cached per header value, which can fragment a CDN cache. Responses chosen from a user, session or cookie are private and shouldn't be cached by a CDN at all. Custom resolvers that read personal data must set their own cache headers.
#Path routes win
On a Route::localized() route, localization does nothing: the path locale is authoritative. To suggest a language on such a page without changing it, use preferred():
1locale()->preferred(); // runs the "web" profile, e.g. "fr", or null2locale()->preferred('api'); // any profile#Custom Resolvers
A resolver is a class implementing LocaleResolver. Return any locale code, or null when it has no preference.
1namespace App\Localization; 2 3use App\Tenancy\TenantRepository; 4use Illuminate\Http\Request; 5use Pharaonic\Laravel\Localization\Contracts\LocaleResolver; 6 7final class TenantLocaleResolver implements LocaleResolver 8{ 9 public function __construct(private TenantRepository $tenants)10 {11 }12 13 public function resolve(Request $request): ?string14 {15 return $this->tenants->forHost($request->getHost())?->locale;16 }17}List the class in a profile where it should run:
1'resolvers' => [2 'api' => [3 App\Localization\TenantLocaleResolver::class,4 'user',5 'header'6 ],7],#Behavior
- The class is resolved from the container on each request, so constructor injection and container bindings work. Keep no request, user or result in properties.
- The value is matched against
supported; unsupported or empty values fall through to the next resolver. locale()->source()reports the class name when it wins.- The class name is stored in the configuration, so
config:cachekeeps working. Closures are not accepted. - An exception thrown by the resolver propagates, and the request fails. Catch it inside the resolver and return
nullwhen a failure should fall through.
#Locale Preferences
Resolving a locale never writes anything. To remember a choice for later requests, call remember() from a route you control, such as a language-picker form.
1use Illuminate\Http\Request; 2use Illuminate\Validation\Rule; 3 4Route::middleware('web')->post('/language', function (Request $request) { 5 $locale = $request->validate([ 6 'locale' => ['required', Rule::in(locale()->supported())], 7 ])['locale']; 8 9 locale()->remember($locale, 'session');10 locale()->remember($locale, 'cookie');11 12 return redirect(locale()->route('home', locale: $locale));13})->name('language');#Stores
| Store | Writes | Needs |
|---|---|---|
session | session.key | A started session (the web group). Otherwise a RuntimeException explains what is missing. |
cookie | A queued cookie named cookie.key | Laravel's cookie middleware: AddQueuedCookiesToResponse sends it, EncryptCookies encrypts it. |
The cookie is HTTP-only, uses the configured lifetime, SameSite (lax by default) and secure flag (null follows session.secure), with Laravel's default path and domain.
#Rules
- The locale is validated first: an unsupported value throws
UnsupportedLocaleException, and the configured spelling is stored (ARis stored asar). - The current request keeps its locale. On a path-localized page, redirect to the URL in the new locale to switch now.
forget('session')andforget('cookie')remove a stored preference.- Nothing writes to the user model. Update your own column, then
preferredLocale()returns it. - The package registers no route of its own. Keep your preference route behind CSRF protection (the
webgroup).
#Signed URLs
Sign localized routes with Laravel's own signer. The URL is generated for the concrete route of the locale, then signed, and nothing changes it afterwards.
1$url = locale()->signedRoute('invites.accept', ['invite' => $invite], locale: 'ar');2 3$url = locale()->temporarySignedRoute('invites.accept', now()->addMinutes(30), ['invite' => $invite], locale: 'fr');4 5$url = locale()->signedRoute('invites.accept', ['invite' => $invite], absolute: false, locale: 'fr');The signatures are signedRoute($name, $parameters = [], $expiration = null, $absolute = true, $locale = null) and temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true, $locale = null).
Protect the route with Laravel's signed middleware:
1use App\Http\Controllers\AcceptInviteController;2 3Route::localized(function (): void {4 Route::get('/invites/{invite}', AcceptInviteController::class)5 ->name('invites.accept')6 ->middleware('signed');7});Protect a route that receives relative signed URLs with signed:relative:
1Route::get('/invites/{invite}', AcceptInviteController::class)2 ->name('invites.accept')3 ->middleware('signed:relative');#What to know
- The signature covers the locale prefix and translated path, so changing
/ar/to/fr/makes it invalid (403). switchUrl()andalternates()return nothing on a signed URL. To offer another language, sign a new URL withlocale()->signedRoute()for that locale.- Canonical redirects change the URL, so a signed URL that goes through
/en/...is no longer valid. Sign the canonical URL, whichlocale()->signedRoute()always does. - The 1.x
URL::LocalizedSignedRoute()andURL::temporaryLocalizedSignedRoute()macros remain as deprecated aliases of these methods.
#Diagnostics
localization:doctor checks the setup and exits with 1 when something is broken, so it can run in CI.
php artisan localization:doctor1[OK] Default locale [en] (app.locale), supported: en, ar, fr.2[OK] Resolver profiles: web, api.3[WARN] Route [api/profile] uses the session resolver without StartSession; it will never match.4[OK] 12 localized routes (4 logical) checked.560 error(s), 1 warning(s).#Checks
| Check | Level |
|---|---|
Configuration: supported locales, app.locale, prefixes, profiles, cookie and header settings, the 1.x file | error |
Configuration that config:cache can't store | error |
Custom resolvers that can't be built or don't implement LocaleResolver | error |
Localized routes whose locales don't match supported (a stale route cache) | error |
| A localized route name that resolves to another route | error |
A localization:{profile} route with an unknown profile | error |
session resolver without StartSession, cookie resolver without EncryptCookies | warning |
The localization alias pointing to another middleware | warning |
The command reads configuration and routes only. It never reads requests, sessions, cookies or users, so it can't print their data.
#API Reference
#locale() methods
locale() returns the Pharaonic\Laravel\Localization\LocalizationManager singleton. It keeps no request state, so it is safe in long-running workers.
| Method | Description | Returns |
|---|---|---|
current() | The active application locale (App::getLocale()) | string |
default() | Laravel's app.locale as configured | string |
source() | What decided the request locale: path, a resolver ID or class, default; null outside a localized request | ?string |
mode() | path or negotiated; null outside a localized request | ?string |
supported() | The supported locale codes | array |
isSupported(string $locale) | Whether the code is supported (no fallback) | bool |
normalize(string $locale) | BCP 47 form; throws InvalidArgumentException when malformed | string |
match(string $locale) | Best supported match | ?string |
name(?string $locale = null) | English display name | string |
nativeName(?string $locale = null) | Display name in the locale itself | string |
direction(?string $locale = null) | ltr or rtl | string |
isRTL(?string $locale = null) | Whether the direction is rtl | bool |
meta(string $key, mixed $default = null, ?string $locale = null) | A metadata value (name, native, direction or a custom key), dot notation | mixed |
metadata(?string $locale = null) | Resolved name, native, direction and every custom key | array<string, mixed> |
route(string $name, mixed $parameters = [], ?string $locale = null, bool $absolute = true) | URL of a localized route | string |
signedRoute(string $name, mixed $parameters = [], $expiration = null, bool $absolute = true, ?string $locale = null) | Signed URL | string |
temporarySignedRoute(string $name, $expiration, mixed $parameters = [], bool $absolute = true, ?string $locale = null) | Expiring signed URL | string |
switchUrl(string $locale) | Current page in a locale, with its query string | ?string |
alternates() | Current page in every available locale | array<string, string> |
hreflangs() | alternates() keyed by BCP 47 tag, plus x-default | array<string, string> |
preferred(string $profile = 'web') | A profile's preferred locale, without applying it | ?string |
remember(string $locale, string $store) | Store a preference in session or cookie | void |
forget(string $store) | Remove a stored preference | void |
Deprecated 1.x aliases: getName(), getNativeName(), getDirection(), isSupportedLocale(), getLanguage(), getRegion().
#Routing and middleware
| Name | Description |
|---|---|
Route::localized(Closure $routes) | Registers the routes once per supported locale |
localization / localization:{profile} | Negotiated-mode middleware alias (SetNegotiatedLocale), profile api by default |
SetPathLocale | Path-mode middleware, attached by Route::localized() |
localized.{locale}.{name} | Reserved route names of non-default variants |
localized.redirect.{name} | Reserved route names of canonical redirects |
localization:doctor | Diagnostics command |
#Contracts
| Interface | Method |
|---|---|
Contracts\LocaleResolver | resolve(Request $request): ?string |
Contracts\HasLocalizedRouteKey | getLocalizedRouteKey(string $locale): ?string |
#Exceptions
| Class | Extends | Thrown when |
|---|---|---|
InvalidLocalizationConfigurationException | LogicException | Invalid configuration, resolver, translation file, or route collision |
UnsupportedLocaleException | InvalidArgumentException | An explicit locale is not supported |
LocalizedRouteNotFoundException | Symfony RouteNotFoundException | The route is missing or not localized |
MissingLocalizedRouteKeyException | RuntimeException | A model has no route key in the locale |
#Publish tags
pharaonic, laravel-localization, pharaonic-config, localization-config.
#Examples
#1. A public website without sessions or cookies
English at /, Arabic at /ar, French at /fr, with canonical redirects for /en/... and hreflang tags.
1'supported' => ['en', 'ar', 'fr'],1use App\Http\Controllers\AboutController;2use App\Http\Controllers\HomeController;3 4Route::localized(function (): void {5 Route::get('/', HomeController::class)->name('home');6 Route::get('/about', AboutController::class)->name('about');7});1<html lang="{{ locale()->normalize(locale()->current()) }}" dir="{{ locale()->direction() }}">2<head>3 @foreach (locale()->hreflangs() as $hreflang => $url)4 <link rel="alternate" hreflang="{{ $hreflang }}" href="{{ $url }}">5 @endforeach6</head>#2. A header-only API
1'resolvers' => [2 'api' => ['header'],3],1use App\Http\Controllers\ApiProductController;2 3Route::middleware('localization')->get('/products', [ApiProductController::class, 'index']);1Accept-Language: ar-EG,ar;q=0.9,en;q=0.8 → ar, source "header"2Accept-Language: de → en (app.locale), source "default"3(no header) → en, source "default"#3. Signed-in users, then the browser
With User implementing HasLocalePreference, the default api profile (user, then header) uses the user's language when they have one:
1use App\Http\Controllers\NotificationController;2 3Route::middleware(['auth:sanctum', 'localization'])->get('/notifications', NotificationController::class);#4. A tenant resolver before everything else
1'resolvers' => [2 'api' => [3 App\Localization\TenantLocaleResolver::class,4 'user',5 'header'6 ],7],1$this->app->bind(TenantLocaleResolver::class, fn ($app) => new TenantLocaleResolver($app->make(TenantRepository::class)));The tenant's locale wins; without one, the user's, then the header's.
#5. Translated paths, localized slugs and deployment
1return ['posts' => 'مقالات'];1use App\Http\Controllers\PostController;2 3Route::localized(function (): void {4 Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');5});php artisan config:cachephp artisan route:cachephp artisan localization:doctorA post with no Arabic slug has no Arabic URL: locale()->route('posts.show', $post, 'ar') throws MissingLocalizedRouteKeyException, and the switcher and hreflang tags leave Arabic out.
#Upgrading from 1.x
12.0 is a redesign. Plan the upgrade route by route; UPGRADING.md in the repository has the full checklist.
#What changed
| 1.x | 12.x |
|---|---|
type = sub-directory | Path mode with Route::localized() |
type = sub-domain or ccTLDs | Removed: use Laravel's Route::domain() and set the locale in your own middleware or a custom resolver |
default | Laravel's app.locale |
| implicit fallback | Laravel's app.fallback_locale, for translation strings only |
hide-default | path.hide_default, true by default |
force-redirect | Removed; /en/... → /... canonical redirect with path.canonical_redirect |
prefixes (api/*) | Removed; put Route::localized() inside your own prefix() group |
list, ccTLDs-list | locales metadata overrides, ext-intl names |
config/Pharaonic/localization.php | config/pharaonic/localization.php; the old file throws with a migration message |
{locale?} route parameter and LocaleRemover | Removed: each locale has its own static route |
locale('ar')->route($name) | locale()->route($name, [], 'ar'); locale('ar') now throws |
locale()->current() returned a URL | Returns the locale code; use locale()->switchUrl(locale()->current()) |
locale()->url($uri), unLocalizedRoute() | Use named routes with locale()->route(), and route() |
URL::LocalizedSignedRoute() | locale()->signedRoute() (the macros remain, deprecated) |
getName(), getNativeName(), getDirection(), isSupportedLocale() | name(), nativeName(), direction(), isSupported() (old names deprecated) |
#Steps
- Delete
config/Pharaonic/localization.php, publish the new file, and copy yoursupportedlist. Make sureapp.localeis in it. - Keep your
Route::localized()groups. Replace closure actions with controllers if you cache routes. - Replace
locale($code)calls and everylocale()->current()used as a URL. - Move sub-domain or ccTLD setups to
Route::domain()groups. - Run
php artisan route:clear, thenphp artisan localization:doctor.
1.x redirected with force-redirect. Browsers may have cached those redirects; test the new URLs in a clean browser, and avoid changing hide_default again after release.
#Troubleshooting
#"app.locale [en] is not in localization.supported"
The default locale must be in supported, spelled exactly as in app.locale (en_US and en-US are different directories for Laravel's translator). Add it, or set supported to null to support only the default.
#"config/Pharaonic/localization.php is the 1.x configuration"
The 1.x file is still in your application. Delete it and publish the new one with php artisan vendor:publish --tag=localization-config.
#/ar/... returns 404 after adding a locale
The route cache was built with the old supported list. Run php artisan route:cache again (or route:clear). localization:doctor reports localized routes that don't match the configuration.
#"Route [x] is not registered inside Route::localized()"
locale()->route() only builds localized routes. Use Laravel's route() for other routes, or move the route inside Route::localized().
#The locale is always the default on an API route
Check that the route has the localization middleware and that a resolver can match. Test requests always send a header: an unsupported Accept-Language falls back to app.locale with source default. A session or cookie resolver needs the web group; the doctor warns when it is missing.
#A preference cookie or session value is ignored on /products
That's intended. A path-localized URL always has its own locale, and /products is always the default language. Link to /ar/products, or use locale()->preferred() to suggest a language.
#Model binding finds nothing under /ar/...
Make resolveRouteBinding() read app()->getLocale(). If your application replaced Laravel's middleware priority list, keep SubstituteBindings in it so the package can run before it.
#"Remembering a locale in the session needs a started session"
The route calling remember(..., 'session') has no session. Add it to the web group, or use the cookie store.
#"Route::localized() cannot register routes while the route cache is loaded"
Routes are being registered at runtime while the cache is active, for example from a package provider. Register localized routes in your routes files.
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Localization!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.