Laravel Packagev6.0.0MIT License

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.

Quick Tip

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.0
  • Laravel 6.x (6.20 or later)
  • ext-intl: it provides locale display names for name() and nativeName()

#Composer Installation

Terminal
composer require pharaonic/laravel-localization

#Publish Configuration

Publish the configuration file to config/pharaonic/localization.php:

Terminal
php artisan vendor:publish --tag=localization-config

Then list your locales. The default locale is Laravel's app.locale and must be one of them:

config/pharaonic/localization.php
1'supported' => ['en', 'ar', 'fr'],

#Check the Setup

Terminal
php artisan localization:doctor
Installation Complete

You're all set! Wrap routes in Route::localized() for localized URLs, or add the localization middleware to API routes.

No database, session or cookies required

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.

ConceptMeaningWhere it comes from
Default localeThe locale of unprefixed URLs, and of negotiation when no source matchesLaravel's app.locale
Translation fallbackThe locale Laravel's translator uses for a missing stringLaravel's app.fallback_locale
Supported localesThe locales routes are registered for and negotiation may picklocalization.supported
Modepath (the URL carries the locale) or negotiated (it doesn't)Route::localized() or the localization middleware
ResolverOne source of a locale preference: user, session, cookie, header or a classlocalization.resolvers
SourceWhich resolver decided the current request, or path / defaultlocale()->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/المنتجات → ar
3/fr/produits → fr
4/en/products → 301 to /products
5/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 next
2Accept-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() or URL::defaults().
App::setLocale() and app.locale

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.

config/pharaonic/localization.php
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

KeyDefaultDescription
supportednullList of locale codes. null supports only app.locale. Must contain app.locale exactly as written there.
path.hide_defaulttrueThe default locale lives at unprefixed URLs. With false, every locale has a prefix and /products is a 404.
path.canonical_redirecttrueWith 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).
resolversweb, apiNamed profiles: ordered lists of user, session, cookie, header or a resolver class name.
session.keylocaleSession key read by the session resolver and written by remember().
cookie.keylocaleCookie name read by the cookie resolver and written by remember().
cookie.minutesone yearLifetime of a remembered cookie.
cookie.same_sitelaxlax, strict, none or null.
cookie.securenullnull uses Laravel's session.secure.
header.nameAccept-LanguageHeader read by the header resolver.
locales[]Optional metadata per locale: name, native, direction (ltr or rtl), and any custom key.
There is no default or fallback 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.

config/pharaonic/localization.php
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.

config/pharaonic/localization.php
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 ar
2locale()->meta('flag.url', locale: 'en'); // "/flags/gb.svg"
3locale()->meta('flag', null, 'fr'); // null: fr has no flag
4locale()->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.

routes/web.php
1use Illuminate\Support\Facades\Route;
2 
3Route::localized(function (): void {
4 Route::get('/', 'ProductController@home')->name('home');
5 Route::get('/products', 'ProductController@index')->name('products.index');
6 Route::get('/products/{product}', 'ProductController@show')->name('products.show');
7});

With supported set to ['en', 'ar', 'fr'] and app.locale set to en, this registers:

URINameLocale
/productsproducts.indexen
/ar/productslocalized.ar.products.indexar
/fr/productslocalized.fr.products.indexfr
/en/products (GET, HEAD)localized.redirect.products.index301 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. Use locale()->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. inside Route::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.

routes/web.php
1Route::middleware('web')->prefix('shop')->name('shop.')->group(function (): void {
2 Route::localized(function (): void {
3 Route::resource('products', 'ProductController')->only(['index', 'show']);
4 });
5});
6 
7// /shop/products shop.products.index
8// /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.

Permanent redirects are cached by browsers

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.

Terminal
php artisan route:cache
php artisan route:list --name=localized.ar
Registration order

Prefixed 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. Each key is one URI segment, each value its translation.

resources/lang/ar/routes.php
1return [
2 'products' => 'المنتجات',
3 'about' => 'من-نحن',
4];
resources/lang/fr/routes.php
1return [
2 'products' => 'produits',
3 'about' => 'a-propos',
4];
routes/web.php
1Route::localized(function (): void {
2 Route::get('/products/{product}', 'ProductController@show')->name('products.show');
3 Route::get('/about', 'AboutController')->name('about');
4});
5 
6// /products/{product} /about
7// /ar/المنتجات/{product} /ar/من-نحن
8// /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 as shop is 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 locale
2locale()->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

SituationException
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 localeMissingLocalizedRouteKeyException

All three live in Pharaonic\Laravel\Localization\Exceptions.

#The current locale

1locale()->current(); // "ar", the active App::getLocale()
2locale()->default(); // "en", app.locale
3locale()->source(); // "path", "user", "session", "cookie", "header", a class name, "default", or null
4locale()->mode(); // "path", "negotiated", or null outside a localized request
5locale()->supported(); // ["en", "ar", "fr"]

#Matching and normalizing

1locale()->isSupported('AR'); // true (case and -/_ insensitive, no fallback)
2locale()->isSupported('ar-EG'); // false
3locale()->match('ar-EG'); // "ar" (exact, then parent, then first configured variant)
4locale()->match('pt'); // "pt_BR" when pt_BR is the first configured pt locale
5locale()->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 locale
4locale()->isRTL('fr'); // false
resources/views/layouts/app.blade.php
1<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.

app/Post.php
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.

Your model decides the lookup

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.

resources/views/partials/language-switcher.blade.php
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 @endif
12 @endforeach
13</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.

resources/views/layouts/app.blade.php
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 @endforeach
6</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.

app/Http/Middleware/AddHreflangLinks.php
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.

routes/api.php
1Route::middleware('localization')->group(function (): void {
2 Route::get('/products', 'ApiProductController@index');
3});

The argument is the profile name: localization uses api, localization:web uses web.

1GET /api/products
2Accept-Language: ar-EG,ar;q=0.9,en;q=0.8
3
4→ 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.

config/pharaonic/localization.php
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 like locale()->match(), so ar_EG from a user becomes ar.
  • Without a match, the locale is app.locale and the source default. app.fallback_locale is 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

IDReadsNotes
user$request->user()->preferredLocale()When the user implements Laravel's HasLocalePreference. No trait or column is required.
sessionsession.keyOnly when the session is already started (the web group). Never starts one.
cookiecookie.keyAs the request carries it: decrypted by EncryptCookies in the web group. Never writes one.
headerAccept-Language (or header.name)Quality values, q=0, *, language-range matching; malformed entries are skipped and parsing is bounded.
app/User.php
1use Illuminate\Contracts\Translation\HasLocalePreference;
2 
3class User extends Authenticatable implements HasLocalePreference
4{
5 public function preferredLocale(): ?string
6 {
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:

routes/api.php
1Route::middleware(['auth:sanctum', 'localization'])->get('/me', 'MeController');

For session and cookie, the route needs the web group (or StartSession and EncryptCookies); localization:doctor warns when they are missing.

#Response headers

  • Content-Language is set to the BCP 47 tag of the locale, unless the response already has one.
  • When the header resolver ran, the header name is added to Vary, keeping existing values.
  • When the user, session or cookie resolver ran, a response marked public or with s-maxage is made private, so a shared cache can't serve one user's language to another. no-store responses and Laravel's default no-cache, private are left alone.
CDNs

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 null
2locale()->preferred('api'); // any profile

#Custom Resolvers

A resolver is a class implementing LocaleResolver. Return any locale code, or null when it has no preference.

app/Localization/TenantLocaleResolver.php
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): ?string
14 {
15 return $this->tenants->forHost($request->getHost())?->locale;
16 }
17}

List the class in a profile where it should run:

config/pharaonic/localization.php
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:cache keeps working. Closures are not accepted.
  • An exception thrown by the resolver propagates, and the request fails. Catch it inside the resolver and return null when 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.

routes/web.php
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

StoreWritesNeeds
sessionsession.keyA started session (the web group). Otherwise a RuntimeException explains what is missing.
cookieA queued cookie named cookie.keyLaravel'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 (AR is stored as ar).
  • The current request keeps its locale. On a path-localized page, redirect to the URL in the new locale to switch now.
  • forget('session') and forget('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 web group).

#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:

routes/web.php
1Route::localized(function (): void {
2 Route::get('/invites/{invite}', 'AcceptInviteController')
3 ->name('invites.accept')
4 ->middleware('signed');
5});

Laravel 6 has no signed:relative middleware. Check a relative URL in the controller instead:

app/Http/Controllers/AcceptInviteController.php
1abort_unless($request->hasValidSignature(false), 403);

#What to know

  • The signature covers the locale prefix and translated path, so changing /ar/ to /fr/ makes it invalid (403).
  • switchUrl() and alternates() return nothing on a signed URL. To offer another language, sign a new URL with locale()->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, which locale()->signedRoute() always does.
  • The 1.x URL::LocalizedSignedRoute() and URL::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.

Terminal
php artisan localization:doctor
1[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.
5
60 error(s), 1 warning(s).

#Checks

CheckLevel
Configuration: supported locales, app.locale, prefixes, profiles, cookie and header settings, the 1.x fileerror
Configuration that config:cache can't storeerror
Custom resolvers that can't be built or don't implement LocaleResolvererror
Localized routes whose locales don't match supported (a stale route cache)error
A localized route name that resolves to another routeerror
A localization:{profile} route with an unknown profileerror
session resolver without StartSession, cookie resolver without EncryptCookieswarning
The localization alias pointing to another middlewarewarning

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.

MethodDescriptionReturns
current()The active application locale (App::getLocale())string
default()Laravel's app.locale as configuredstring
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 codesarray
isSupported(string $locale)Whether the code is supported (no fallback)bool
normalize(string $locale)BCP 47 form; throws InvalidArgumentException when malformedstring
match(string $locale)Best supported match?string
name(?string $locale = null)English display namestring
nativeName(?string $locale = null)Display name in the locale itselfstring
direction(?string $locale = null)ltr or rtlstring
isRTL(?string $locale = null)Whether the direction is rtlbool
meta(string $key, mixed $default = null, ?string $locale = null)A metadata value (name, native, direction or a custom key), dot notationmixed
metadata(?string $locale = null)Resolved name, native, direction and every custom keyarray<string, mixed>
route(string $name, mixed $parameters = [], ?string $locale = null, bool $absolute = true)URL of a localized routestring
signedRoute(string $name, mixed $parameters = [], $expiration = null, bool $absolute = true, ?string $locale = null)Signed URLstring
temporarySignedRoute(string $name, $expiration, mixed $parameters = [], bool $absolute = true, ?string $locale = null)Expiring signed URLstring
switchUrl(string $locale)Current page in a locale, with its query string?string
alternates()Current page in every available localearray<string, string>
hreflangs()alternates() keyed by BCP 47 tag, plus x-defaultarray<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 cookievoid
forget(string $store)Remove a stored preferencevoid

Deprecated 1.x aliases: getName(), getNativeName(), getDirection(), isSupportedLocale(), getLanguage(), getRegion().

#Routing and middleware

NameDescription
Route::localized(Closure $routes)Registers the routes once per supported locale
localization / localization:{profile}Negotiated-mode middleware alias (SetNegotiatedLocale), profile api by default
SetPathLocalePath-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:doctorDiagnostics command

#Contracts

InterfaceMethod
Contracts\LocaleResolverresolve(Request $request): ?string
Contracts\HasLocalizedRouteKeygetLocalizedRouteKey(string $locale): ?string

#Exceptions

ClassExtendsThrown when
InvalidLocalizationConfigurationExceptionLogicExceptionInvalid configuration, resolver, translation file, or route collision
UnsupportedLocaleExceptionInvalidArgumentExceptionAn explicit locale is not supported
LocalizedRouteNotFoundExceptionSymfony RouteNotFoundExceptionThe route is missing or not localized
MissingLocalizedRouteKeyExceptionRuntimeExceptionA 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.

config/pharaonic/localization.php
1'supported' => ['en', 'ar', 'fr'],
routes/web.php
1Route::localized(function (): void {
2 Route::get('/', 'HomeController')->name('home');
3 Route::get('/about', 'AboutController')->name('about');
4});
resources/views/layouts/app.blade.php
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 @endforeach
6</head>

#2. A header-only API

config/pharaonic/localization.php
1'resolvers' => [
2 'api' => ['header'],
3],
routes/api.php
1Route::middleware('localization')->get('/products', 'ApiProductController@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:

routes/api.php
1Route::middleware(['auth:sanctum', 'localization'])->get('/notifications', 'NotificationController');

#4. A tenant resolver before everything else

config/pharaonic/localization.php
1'resolvers' => [
2 'api' => [
3 App\Localization\TenantLocaleResolver::class,
4 'user',
5 'header'
6 ],
7],
app/Providers/AppServiceProvider.php
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

resources/lang/ar/routes.php
1return ['posts' => 'مقالات'];
routes/web.php
1Route::localized(function (): void {
2 Route::get('/posts/{post}', 'PostController@show')->name('posts.show');
3});
Terminal
php artisan config:cache
php artisan route:cache
php artisan localization:doctor

A 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

6.0 is a redesign. Plan the upgrade route by route; UPGRADING.md in the repository has the full checklist.

#What changed

1.x6.x
type = sub-directoryPath mode with Route::localized()
type = sub-domain or ccTLDsRemoved: use Laravel's Route::domain() and set the locale in your own middleware or a custom resolver
defaultLaravel's app.locale
implicit fallbackLaravel's app.fallback_locale, for translation strings only
hide-defaultpath.hide_default, true by default
force-redirectRemoved; /en/... → /... canonical redirect with path.canonical_redirect
prefixes (api/*)Removed; put Route::localized() inside your own prefix() group
list, ccTLDs-listlocales metadata overrides, ext-intl names
config/Pharaonic/localization.phpconfig/pharaonic/localization.php; the old file throws with a migration message
{locale?} route parameter and LocaleRemoverRemoved: each locale has its own static route
locale('ar')->route($name)locale()->route($name, [], 'ar'); locale('ar') now throws
locale()->current() returned a URLReturns 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

  1. Delete config/Pharaonic/localization.php, publish the new file, and copy your supported list. Make sure app.locale is in it.
  2. Keep your Route::localized() groups. Replace closure actions with controllers if you cache routes.
  3. Replace locale($code) calls and every locale()->current() used as a URL.
  4. Move sub-domain or ccTLD setups to Route::domain() groups.
  5. Run php artisan route:clear, then php artisan localization:doctor.
Cached redirects

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.

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!

Moamen Eltouny

@MoamenEltouny

95 contributions

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.