[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-8493":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":19,"rankGlobal":10,"rankLanguage":10,"license":20,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":21,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":29,"readmeContent":30,"aiSummary":31,"trendingCount":16,"starSnapshotCount":16,"syncStatus":32,"lastSyncTime":33,"discoverSource":34},8493,"laravel-localization","mcamara\u002Flaravel-localization","mcamara","Easy localization for Laravel","",null,"PHP",3559,514,88,29,0,1,7,30.14,"MIT License",false,"master",true,[25,26,5,27,28],"language-selector","laravel","laravel-package","php","2026-06-12 02:01:54","# Laravel Localization\n\n[![Latest Version on Packagist](https:\u002F\u002Fimg.shields.io\u002Fpackagist\u002Fv\u002Fmcamara\u002Flaravel-localization.svg?style=flat-square)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fmcamara\u002Flaravel-localization)\n[![Total Downloads](https:\u002F\u002Fimg.shields.io\u002Fpackagist\u002Fdt\u002Fmcamara\u002Flaravel-localization.svg?style=flat-square)](https:\u002F\u002Fpackagist.org\u002Fpackages\u002Fmcamara\u002Flaravel-localization)\n![GitHub Actions](https:\u002F\u002Fgithub.com\u002Fmcamara\u002Flaravel-localization\u002Factions\u002Fworkflows\u002Frun-tests.yml\u002Fbadge.svg)\n[![Open Source Helpers](https:\u002F\u002Fwww.codetriage.com\u002Fmcamara\u002Flaravel-localization\u002Fbadges\u002Fusers.svg)](https:\u002F\u002Fwww.codetriage.com\u002Fmcamara\u002Flaravel-localization)\n[![Reviewed by Hound](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FReviewed_by-Hound-8E64B0.svg)](https:\u002F\u002Fhoundci.com)\n\n> **Architecture note & recommended successor**\n>\n> This package generates routes dynamically per request, which has a\n> number of side effects - most notably, `php artisan route:cache`\n> isn't supported out of the box. For new projects or apps planning to\n> migrate,\n> [**niels-numbers\u002Flaravel-localizer**](https:\u002F\u002Fgithub.com\u002Fniels-numbers\u002Flaravel-localizer)\n> is the recommended modern successor - same feature set, but with\n> statically registered routes that support `route:cache` natively. See\n> the [migration guide](https:\u002F\u002Flocalizer.adam-nielsen.de\u002Fmigrating-from-laravel-localization)\n> for the swap.\n>\n> This package remains actively maintained by\n> [@jordyvanderhaegen](https:\u002F\u002Fgithub.com\u002Fjordyvanderhaegen) for users\n> who need to stay on the current architecture. Compatibility updates\n> (Laravel\u002FPHP versions, security, small bug fixes) continue here.\n\nEasy i18n localization for Laravel, an useful tool to combine with Laravel localization classes.\n\nThe package offers the following:\n\n - Detect language from browser\n - Smart redirects (Save locale in session\u002Fcookie)\n - Smart routing (Define your routes only once, no matter how many languages you use)\n - Translatable Routes\n - Supports caching & testing\n - Option to hide default locale in url\n - Many snippets and helpers (like language selector)\n\n## Table of Contents\n\n- \u003Ca href=\"#installation\">Installation\u003C\u002Fa>\n- \u003Ca href=\"#usage\">Usage\u003C\u002Fa>\n- \u003Ca href=\"#redirect-middleware\">Redirect Middleware\u003C\u002Fa>\n- \u003Ca href=\"#helpers\">Helpers\u003C\u002Fa>\n- \u003Ca href=\"#translated-routes\">Translated Routes\u003C\u002Fa>\n- \u003Ca href=\"#caching-routes\">Caching routes\u003C\u002Fa>\n- \u003Ca href=\"#testing\">Testing\u003C\u002Fa>\n- \u003Ca href=\"#common-issues\">Common Issues\u003C\u002Fa>\n    - \u003Ca href=\"#post-is-not-working\">POST is not working\u003C\u002Fa>\n    - \u003Ca href=\"#methodnotallowedhttpexception\">MethodNotAllowedHttpException\u003C\u002Fa>\n    - \u003Ca href=\"#validation-message-is-only-in-default-locale\">Validation message is always in default locale\u003C\u002Fa>\n- \u003Ca href=\"#collaborators\">Collaborators\u003C\u002Fa>\n- \u003Ca href=\"#changelog\">Changelog\u003C\u002Fa>\n- \u003Ca href=\"#license\">License\u003C\u002Fa>\n\n## Laravel compatibility\n\n Laravel      | laravel-localization\n:-------------|:----------\n 4.0.x        | 0.13.x\n 4.1.x        | 0.13.x\n 4.2.x        | 0.15.x\n 5.0.x\u002F5.1.x  | 1.0.x\n 5.2.x-5.4.x (PHP 7 not required)  | 1.2.x\n 5.2.0-6.x (PHP version >= 7 required) | 1.4.x\n 6.x-10.x (PHP version >= 7 required) | 1.8.x\n 10.x-13.x (PHP version >= 8.2 required) | 2.0.x\n\n## Installation\n\nInstall the package via composer: `composer require mcamara\u002Flaravel-localization`\n\nFor Laravel 5.4 and below it necessary to [register the service provider](\u002FADDITIONS.md#for-laravel-5.4-and-below).\n\n### Config Files\n\nIn order to edit the default configuration you may execute:\n\n```\nphp artisan vendor:publish --provider=\"Mcamara\\LaravelLocalization\\LaravelLocalizationServiceProvider\"\n```\n\nAfter that, `config\u002Flaravellocalization.php` will be created.\n\nThe configuration options are:\n\n - **supportedLocales** Languages of your app (Default: English & Spanish).\n - **useAcceptLanguageHeader** If true, then automatically detect language from browser.\n - **hideDefaultLocaleInURL** If true, then do not show default locale in url.\n - **localesOrder** Sort languages in custom order.\n - **localesMapping** Rename url locales.\n - **utf8suffix** Allow changing utf8suffix for CentOS etc.\n - **urlsIgnored** Ignore specific urls.\n\n### Register Middleware\n\nYou may register the package middleware in the `app\u002FHttp\u002FKernel.php` file:\n\n```php\n\u003C?php namespace App\\Http;\n\nuse Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\nclass Kernel extends HttpKernel {\n    \u002F**\n    * The application's route middleware.\n    *\n    * @var array\n    *\u002F\n    protected $middlewareAliases = [\n        \u002F**** OTHER MIDDLEWARE ****\u002F\n        'localize'                => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRoutes::class,\n        'localizationRedirect'    => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRedirectFilter::class,\n        'localeSessionRedirect'   => \\Mcamara\\LaravelLocalization\\Middleware\\LocaleSessionRedirect::class,\n        'localeCookieRedirect'    => \\Mcamara\\LaravelLocalization\\Middleware\\LocaleCookieRedirect::class,\n        'localeViewPath'          => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationViewPath::class\n    ];\n}\n```\n\nIf you are using Laravel 11, you may register in `bootstrap\u002Fapp.php` file in closure `withMiddleware`:\n\n```php\nreturn Application::configure(basePath: dirname(__DIR__))\n    \u002F\u002F Other application configurations\n    ->withMiddleware(function (Middleware $middleware) {\n        $middleware->alias([\n            \u002F**** OTHER MIDDLEWARE ALIASES ****\u002F\n            'localize'                => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRoutes::class,\n            'localizationRedirect'    => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationRedirectFilter::class,\n            'localeSessionRedirect'   => \\Mcamara\\LaravelLocalization\\Middleware\\LocaleSessionRedirect::class,\n            'localeCookieRedirect'    => \\Mcamara\\LaravelLocalization\\Middleware\\LocaleCookieRedirect::class,\n            'localeViewPath'          => \\Mcamara\\LaravelLocalization\\Middleware\\LaravelLocalizationViewPath::class,\n        ]);\n    })\n```\n\n## Usage\n\nAdd the following to your routes file:\n\n```php\n\u002F\u002F routes\u002Fweb.php\n\nRoute::group(['prefix' => LaravelLocalization::setLocale()], function()\n{\n\t\u002F** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **\u002F\n\tRoute::get('\u002F', function()\n\t{\n\t\treturn View::make('hello');\n\t});\n\n\tRoute::get('test',function(){\n\t\treturn View::make('test');\n\t});\n});\n\n\u002F** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **\u002F\n\n```\n\nOnce this route group is added to the routes file, a user can access all locales added into `supportedLocales` (`en` and `es` by default).\nFor example, the above route file creates the following addresses:\n\n```\n\u002F\u002F Set application language to English\nhttp:\u002F\u002Furl-to-laravel\u002Fen\nhttp:\u002F\u002Furl-to-laravel\u002Fen\u002Ftest\n\n\u002F\u002F Set application language to Spanish\nhttp:\u002F\u002Furl-to-laravel\u002Fes\nhttp:\u002F\u002Furl-to-laravel\u002Fes\u002Ftest\n\n\u002F\u002F Set application language to English or Spanish (depending on browsers default locales)\n\u002F\u002F if nothing found set to default locale\nhttp:\u002F\u002Furl-to-laravel\nhttp:\u002F\u002Furl-to-laravel\u002Ftest\n```\nThe package sets your application locale `App::getLocale()` according to your url. The locale may then be used for [Laravel's localization features](http:\u002F\u002Flaravel.com\u002Fdocs\u002Flocalization).\n\nYou may add middleware to your group like this:\n\n```php\nRoute::group(\n[\n\t'prefix' => LaravelLocalization::setLocale(),\n\t'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]\n], function(){ \u002F\u002F...\n});\n```\n\n### Recommendations\n\n***1.***: It is **strongly** recommended to use a [redirecting middleware](#redirect-middleware).\nUrls without locale should only be used to determine browser\u002Fdefault locale and to redirect to the [localized url](#localized-urls).\nOtherwise, when search engine robots crawl for example `http:\u002F\u002Furl-to-laravel\u002Ftest` they may get different language content for each visit.\nAlso having multiple urls for the same content creates a SEO duplicate-content issue.\n\n***2.***: It is **strongly** recommended to [localize your links](#localized-urls), even if you use a redirect middleware.\nOtherwise, you will cause at least one redirect each time a user clicks on a link.\nAlso, any action url from a post form must be localized, to prevent that it gets redirected to a get request.\n\n\n## Redirect Middleware\n\nThe following redirection middleware depends on the settings of `hideDefaultLocaleInURL`\nand `useAcceptLanguageHeader` in `config\u002Flaravellocalization.php`:\n\n### LocaleSessionRedirect\n\nWhenever a locale is present in the url, it will be stored in the session by this middleware.\n\nIf there is no locale present in the url, then this middleware will check the following\n\n - If no locale is saved in session and `useAcceptLanguageHeader` is set to true, compute locale from browser and redirect to url with locale.\n - If a locale is saved in session redirect to url with locale, unless its the default locale and `hideDefaultLocaleInURL` is set to true.\n\nFor example, if a user navigates to http:\u002F\u002Furl-to-laravel\u002Ftest  and `en` is the current locale, it would redirect him automatically to http:\u002F\u002Furl-to-laravel\u002Fen\u002Ftest.\n\n### LocaleCookieRedirect\n\nSimilar to LocaleSessionRedirect, but it stores value in a cookie instead of a session.\n\nWhenever a locale is present in the url, it will be stored in the cookie by this middleware.\n\nIn there is no locale present in the url, then this middleware will check the following\n\n - If no locale is saved in cookie and `useAcceptLanguageHeader` is set to true, compute locale from browser and redirect to url with locale.\n - If a locale is saved in cookie redirect to url with locale, unless its the default locale and `hideDefaultLocaleInURL` is set to true.\n\nFor example, if a user navigates to http:\u002F\u002Furl-to-laravel\u002Ftest  and `de` is the current locale, it would redirect him automatically to http:\u002F\u002Furl-to-laravel\u002Fde\u002Ftest.\n\n\n### LaravelLocalizationRedirectFilter\n\nWhen the default locale is present in the url and `hideDefaultLocaleInURL` is set to true, then the middleware redirects to the url without locale.\n\nFor example, if `es` is the default locale, then http:\u002F\u002Furl-to-laravel\u002Fes\u002Ftest would be redirected to http:\u002F\u002Furl-to-laravel\u002Ftest and the`App::getLocale()` would be\nset to `es`.\n\n\n## Helpers\n\nThis package comes with a bunch of helpers.\n\n### Localized URLs\nLocalized URLS  taken into account [route model binding]([https:\u002F\u002Flaravel.com\u002Fdocs\u002Fmaster\u002Frouting#route-model-binding]) when generating the localized route,\naswell as the `hideDefaultLocaleInURL` and [Translated Routes](#translated-routes) settings.\n\n\n#### Get localized URL\n\n```php\n    \u002F\u002F If current locale is Spanish, it returns `\u002Fes\u002Ftest`\n    \u003Ca href=\"{{ LaravelLocalization::localizeUrl('\u002Ftest') }}\">@lang('Follow this link')\u003C\u002Fa>\n```\n\n#### Get localized URL for an specific locale\nGet current URL in specific locale:\n\n```php\n\u002F\u002F Returns current url with English locale.\n{{ LaravelLocalization::getLocalizedURL('en') }}\n```\n\n### Get Clean routes\n\nReturns a URL clean of any localization.\n\n```php\n\u002F\u002F Returns \u002Fabout\n{{ LaravelLocalization::getNonLocalizedURL('\u002Fes\u002Fabout') }}\n```\n\n### Get URL for an specific translation key\n\nReturns a route, [localized](#translated-routes) to the desired locale. If the translation key does not exist in the locale given, this function will return false.\n\n\n```php\n\u002F\u002F Returns \u002Fes\u002Facerca\n{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }}\n```\n**Example of a localized link using routes with attributes**\n\n```php\n\u002F\u002F An array of attributes can be provided.\n\u002F\u002F Returns \u002Fen\u002Farchive\u002Fghosts, \u002Ffr\u002Farchive\u002Ffantômes, \u002Fpt\u002Farquivo\u002Ffantasmas, etc.\n\u003Ca href=\"{{ LaravelLocalization::getURLFromRouteNameTranslated( App::currentLocale(), 'routes.archive', array('category' => 'ghosts')) }}\">Ghost Stories\u003C\u002Fa>\n```\n\n\n### Get Supported Locales\n\nReturn all supported locales and their properties as an array.\n\n```php\n{{ LaravelLocalization::getSupportedLocales() }}\n```\n\n\n\n### Get Supported Locales Custom Order\n\nReturn all supported locales but in the order specified in the configuration file. You can use this function to print locales in the language selector.\n\n```php\n{{ LaravelLocalization::getLocalesOrder() }}\n```\n\n### Get Supported Locales Keys\n\nReturn an array with all the keys for the supported locales.\n\n```php\n{{ LaravelLocalization::getSupportedLanguagesKeys() }}\n```\n\n### Get Current Locale\n\nReturn the key of the current locale.\n\n```php\n{{ LaravelLocalization::getCurrentLocale() }}\n```\n\n### Get Current Locale Name\nReturn current locale's name as string (English\u002FSpanish\u002FArabic\u002F ..etc).\n\n```php\n{{ LaravelLocalization::getCurrentLocaleName() }}\n```\n\n### Get Current Locale Native Name\nReturn current locale's native name as string (English\u002FEspañol\u002Fعربى\u002F ..etc).\n\n```php\n{{ LaravelLocalization::getCurrentLocaleNative() }}\n```\n\n### Get Current Locale Regional Name\nReturn current locale's regional name as string (en_GB\u002Fen_US\u002Ffr_FR\u002F ..etc).\n\n```php\n{{ LaravelLocalization::getCurrentLocaleRegional() }}\n```\n\n### Get Current Locale Direction\n\nReturn current locale's direction as string (ltr\u002Frtl).\n\n\n```php\n{{ LaravelLocalization::getCurrentLocaleDirection() }}\n```\n\n\n\n### Get Current Locale Script\nReturn the [ISO 15924](http:\u002F\u002Fwww.unicode.org\u002Fiso15924) code for the current locale script as a string; \"Latn\", \"Cyrl\", \"Arab\", etc.\n\n```php\n{{ LaravelLocalization::getCurrentLocaleScript() }}\n```\n\n### Set view-base-path to current locale\n\nRegister the middleware `LaravelLocalizationViewPath` to set current locale as view-base-path.\n\nNow you can wrap your views in language-based folders like the translation files.\n\n`resources\u002Fviews\u002Fen\u002F`, `resources\u002Fviews\u002Ffr`, ...\n\n\n### Map your own custom lang url segments\n\nAs you can modify the supportedLocales even by renaming their keys, it is possible to use the string ```uk``` instead of ```en-GB``` to provide custom lang url segments. Of course, you need to prevent any collisions with already existing keys and should stick to the convention as long as possible. But if you are using such a custom key, you have to store your mapping to the ```localesMapping``` array. This ```\nlocalesMapping``` is needed to enable the LanguageNegotiator to correctly assign the desired locales based on HTTP Accept Language Header. Here is a quick example how to map HTTP Accept Language Header 'en-GB' to url segment 'uk':\n\n```php\n\u002F\u002F config\u002Flaravellocalization.php\n\n'localesMapping' => [\n\t'en-GB' => 'uk'\n],\n```\n\nAfter that ```http:\u002F\u002Furl-to-laravel\u002Fen-GB\u002Fa\u002Fb\u002Fc``` becomes ```http:\u002F\u002Furl-to-laravel\u002Fuk\u002Fa\u002Fb\u002Fc```.\n\n```php\nLaravelLocalization::getLocalizedURL('en-GB', 'a\u002Fb\u002Fc'); \u002F\u002F http:\u002F\u002Furl-to-laravel\u002Fuk\u002Fa\u002Fb\u002Fc\nLaravelLocalization::getLocalizedURL('uk', 'a\u002Fb\u002Fc'); \u002F\u002F http:\u002F\u002Furl-to-laravel\u002Fuk\u002Fa\u002Fb\u002Fc\n```\n\n## Creating a language selector\n\nIf you're supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector.\n\n```blade\n\u003Cul>\n    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)\n        \u003Cli>\n            \u003Ca rel=\"alternate\" hreflang=\"{{ $localeCode }}\" href=\"{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}\">\n                {{ $properties['native'] }}\n            \u003C\u002Fa>\n        \u003C\u002Fli>\n    @endforeach\n\u003C\u002Ful>\n```\nHere default language will be forced in getLocalizedURL() to be present in the URL even `hideDefaultLocaleInURL = true`.\n\nNote that Route Model Binding is supported.\n\n## Translated Routes\n\nYou may translate your routes. For example, http:\u002F\u002Furl\u002Fen\u002Fabout and http:\u002F\u002Furl\u002Fes\u002Facerca (acerca is about in spanish)\nor http:\u002F\u002Furl\u002Fen\u002Farticle\u002Fimportant-article and http:\u002F\u002Furl\u002Fes\u002Farticulo\u002Fimportant-article (article is articulo in spanish) would be redirected to the same controller\u002Fview as follows:\n\nIt is necessary that at least the `localize` middleware in loaded in your `Route::group` middleware (See [installation instruction](#installation)).\n\nFor each language, add a `routes.php` into `resources\u002Flang\u002F**\u002Froutes.php` folder.\nThe file contains an array with all translatable routes. For example, like this:\n\n> Keep in mind: starting from [Laravel 9](https:\u002F\u002Flaravel.com\u002Fdocs\u002F9.x\u002Fupgrade#the-lang-directory), the `resources\u002Flang` folder is now located in the root project folder (`lang`).\n> If your project has `lang` folder in the root, you must add a `routes.php` into `lang\u002F**\u002Froutes.php` folder.\n\n```php\n\u003C?php\n\u002F\u002F resources\u002Flang\u002Fen\u002Froutes.php\nreturn [\n    \"about\"    =>  \"about\",\n    \"article\"  =>  \"article\u002F{article}\",\n];\n```\n```php\n\u003C?php\n\u002F\u002F resources\u002Flang\u002Fes\u002Froutes.php\nreturn [\n    \"about\"    =>  \"acerca\",\n    \"article\"  =>  \"articulo\u002F{article}\",\n];\n```\n\nYou may add the routes in `routes\u002Fweb.php` like this:\n\n```php\nRoute::group(['prefix' => LaravelLocalization::setLocale(),\n              'middleware' => [ 'localize' ]], function () {\n\n    Route::get(LaravelLocalization::transRoute('routes.about'), function () {\n        return view('about');\n    });\n\n    Route::get(LaravelLocalization::transRoute('routes.article'), function (\\App\\Article $article) {\n        return $article;\n    });\n\n    \u002F\u002F,...\n});\n```\n\nOnce files are saved, you can access http:\u002F\u002Furl\u002Fen\u002Fabout , http:\u002F\u002Furl\u002Fes\u002Facerca , http:\u002F\u002Furl\u002Fen\u002Farticle\u002Fimportant-article and http:\u002F\u002Furl\u002Fes\u002Farticulo\u002Fimportant-article without any problem.\n\n### Translatable route parameters\n\nMaybe you noticed in the previous example the English slug in the Spanish url:\n\n    http:\u002F\u002Furl\u002Fes\u002Farticulo\u002Fimportant-article\n\nIt is possible to have translated slugs, for example like this:\n\n    http:\u002F\u002Furl\u002Fen\u002Farticle\u002Fimportant-change\n    http:\u002F\u002Furl\u002Fes\u002Farticulo\u002Fcambio-importante\n\nHowever, in order to do this, each article must have many slugs (one for each locale).\nIts up to you how you want to implement this relation. The only requirement for translatable route parameters is, that the relevant model implements the interface `LocalizedUrlRoutable`.\n\n#### Implementing LocalizedUrlRoutable\n\nTo implement `\\Mcamara\\LaravelLocalization\\Interfaces\\LocalizedUrlRoutable`,\none has to create the function `getLocalizedRouteKey($locale)`, which must return for a given locale the translated slug. In the above example, inside the model article, `getLocalizedRouteKey('en')` should return `important-change` and `getLocalizedRouteKey('es')` should return `cambio-importante`.\n\n#### Route Model Binding\n\nTo use [route-model-binding](https:\u002F\u002Flaravel.com\u002Fdocs\u002Frouting#route-model-binding), one  should overwrite the function `resolveRouteBinding($slug)`\nin the model. The function should return the model that belongs to the translated slug `$slug`.\nFor example:\n\n```php\npublic function resolveRouteBinding($slug)\n{\n        return static::findByLocalizedSlug($slug)->first() ?? abort(404);\n}\n```\n\n#### Tutorial Video\n\nYou may want to checkout this [video](https:\u002F\u002Fyoutu.be\u002FB1AUqCdizgc) which demonstrates how one may set up translatable route parameters.\n\n## Events\n\nYou can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the `routes.translation` event like so:\n\n```php\nEvent::listen('routes.translation', function($locale, $attributes)\n{\n\t\u002F\u002F Do your magic\n\n\treturn $attributes;\n});\n```\n\nBe sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: [http:\u002F\u002Flaravel.com\u002Fdocs\u002Fevents#event-subscribers](http:\u002F\u002Flaravel.com\u002Fdocs\u002Fevents#event-subscribers)\n\n## Caching routes\n\n> [!CAUTION]\n> By default, this package is not compatible with Laravel’s route caching.\n> Running commands such as `php artisan route:cache` or `php artisan optimize` will cause localized routes to return 404 errors.\n\nTo enable route caching for your localized routes, you may use the `LoadsTranslatedCachedRoutes` trait provided by this package.\nDepending on your Laravel version, you will need to apply the trait differently:\n\n**Before Laravel 11**    \nIf your application includes a `RouteServiceProvider`, add the `LoadsTranslatedCachedRoutes` trait to it:\n\n```php\nuse Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider as ServiceProvider;\nuse Mcamara\\LaravelLocalization\\Traits\\LoadsTranslatedCachedRoutes;\n\nclass RouteServiceProvider extends ServiceProvider\n{\n    use LoadsTranslatedCachedRoutes;\n}\n```\n\n**After Laravel 11**    \nFor Laravel 11 and newer, add the `LoadsTranslatedCachedRoutes` trait to your `AppServiceProvider`, and register the cached routes within the boot method:\n\n```php\nuse Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider;\nuse Illuminate\\Support\\ServiceProvider;\nuse Mcamara\\LaravelLocalization\\Traits\\LoadsTranslatedCachedRoutes;\n\nclass AppServiceProvider extends ServiceProvider\n{\n    use LoadsTranslatedCachedRoutes;\n\n    public function boot(): void\n    {\n        RouteServiceProvider::loadCachedRoutesUsing(fn () => $this->loadCachedRoutes());\n\n        \u002F\u002F ...\n    }\n}\n```\n\nOnce configured, use the following command to cache your localized routes instead of `php artisan route:cache`:\n```bash\nphp artisan route:trans:cache\n```\n\nTo clear the localized route cache, use:\n```bash\nphp artisan route:trans:clear\n```\n\nTo get a list of routes for a given locale, use:\n```bash\nphp artisan route:trans:list {locale}\n\n# Example:\nphp artisan route:trans:list en\n```\n\n## Common Issues\n\n### POST is not working\n\nThis may happen if you do not localize your action route that is inside your `Routes::group`.\nThis may cause a redirect, which then changes the post request into a get request.\nTo prevent that, simply use the [localize helper](#get-localized-url).\n\nFor example, if you use `Auth::routes()` and put them into your `Route::group` Then\n\n```\n\u003Cform action=\"\u002Flogout\" method=\"POST\">\n\u003Cbutton>Logout\u003C\u002Fbutton>\n\u003C\u002Fform>\n```\n\nwill not work. Instead, one has to use\n\n```php\n\u003Cform action=\"{{  \\LaravelLocalization::localizeURL('\u002Flogout') }} \" method=\"POST\">\n\u003Cbutton>Logout\u003C\u002Fbutton>\n\u003C\u002Fform>\n```\n\n\nAnother way to solve this is to put http method to config to 'laravellocalization.httpMethodsIgnored'\nto prevent of processing this type of requests\n\n### MethodNotAllowedHttpException\n\nIf you do not localize your post url and use a redirect middleware,\nthen the post request gets redirected as a get request.\nIf you have not defined such a get route, you will cause this exception.\n\nTo localize your post url see the example in [POST is not working](#post-is-not-working).\n\n### Validation message is only in default locale\n\nThis also happens if you did not localize your post url.\nIf you don't localize your post url, the default locale is set while validating,\nand when returning to `back()` it shows the validation message in default locale.\n\nTo localize your post url see the example in [POST is not working](#post-is-not-working).\n\n## Testing\n\nIn a typical request lifecycle, your application is bootstrapped automatically — allowing this package to detect the active route and set the appropriate locale.\nHowever, when running tests, the application is bootstrapped before any request is made. As a result, the package can’t determine the current route, which often leads to a `404` error.\n\nTo handle this, you can manually define the locale prefix in your tests by refreshing the application with a specific locale:\n\n### PHPUnit\n```php\nuse Illuminate\\Foundation\\Testing\\TestCase as BaseTestCase;\nuse Mcamara\\LaravelLocalization\\LaravelLocalization;\n\nabstract class TestCase extends BaseTestCase\n{\n    protected function refreshApplicationWithLocale(string $locale): void\n    {\n        self::tearDown();\n        putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);\n        self::setUp();\n    }\n\n    protected function tearDown(): void\n    {\n        putenv(LaravelLocalization::ENV_ROUTE_KEY);\n        parent::tearDown();\n    }\n}\n```\n\n```php\nfinal class HomeControllerTest extends TestCase\n{\n    public function it_can_visit_the_home_page()\n    {\n        $this->refreshApplicationWithLocale('en');\n\n        $response = $this->get('\u002Fen');\n\n        $response->assertStatus(200);\n    }\n}\n```\n\n### Pest\n```php\n\u002F\u002F Pest.php\nuse Mcamara\\LaravelLocalization\\LaravelLocalization;\n\nfunction refreshApplicationWithLocale(string $locale): void\n{\n    \u002F** @var \\Tests\\TestCase $test *\u002F\n    $test = test();\n\n    $test->tearDown();\n    putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);\n    $test->setUp();\n}\n\npest()->afterEach(function () {\n    putenv(LaravelLocalization::ENV_ROUTE_KEY);\n});\n```\n```php\n\u002F\u002F YourTest.php\ntest('it can visit the home page', function () {\n    refreshApplicationWithLocale('en');\n\n    $response = $this->get('\u002Fen');\n\n    $response->assertStatus(200);\n});\n```\n\n\n## Collaborators\n- [Adam Nielsen (iwasherefirst2)](https:\u002F\u002Fgithub.com\u002Fiwasherefirst2)\n\nAsk [mcamara](https:\u002F\u002Fgithub.com\u002Fmcamara) if you want to be one of them!\n\n## Changelog\n\nView changelog here -> [changelog](CHANGELOG.md)\n\n## License\n\nLaravel Localization is an open-sourced laravel package licensed under the MIT license\n","mcamara\u002Flaravel-localization 是一个为 Laravel 框架提供便捷国际化支持的 PHP 包。它具备自动检测浏览器语言、智能重定向（保存用户偏好至会话或 cookie）、一次定义多语言路由等功能，并且支持缓存和测试，同时提供了诸如隐藏默认语言标识等选项及多种辅助函数。此工具特别适合需要构建多语言版本网站的应用场景，能够显著简化开发者在处理国际化时的工作量。尽管存在一些架构上的限制，如不直接支持 `php artisan route:cache` 命令，但该项目仍由社区积极维护并持续更新以保持与最新版 Laravel 和 PHP 的兼容性。对于正在寻找更现代解决方案的新项目，推荐考虑其官方建议的替代方案 niels-numbers\u002Flaravel-localizer。",2,"2026-06-11 03:18:17","top_language"]