⭐️ 在 Laravel 应用中设置和使用本地化路由的便捷方式。
A convenient way to set up and use localized routes in a Laravel app.
Upgrading to a new major version? Check our upgrade guide for instructions.
Install this package with Composer:
composer require codezero/laravel-localized-routesLaravel will automatically register the ServiceProvider.
php artisan vendor:publish --provider="CodeZero\LocalizedRoutes\LocalizedRoutesServiceProvider" --tag="config"You will now find a localized-routes.php file in the config folder.
Add any locales you wish to support to your published config/localized-routes.php file:
'supported_locales' => ['en', 'nl'];These locales will be used as a slug, prepended to the URL of your localized routes.
You can also use a custom slug for a locale:
'supported_locales' => [
'en' => 'english-slug',
'nl' => 'dutch-slug',
];Or you can use a custom domain for a locale:
'supported_locales' => [
'en' => 'english-domain.test',
'nl' => 'dutch-domain.test',
];When using the route() helper to generate a URL for a locale that is not supported, a Symfony\Component\Routing\Exception\RouteNotFoundException is thrown by Laravel.
However, you can configure a fallback locale to attempt to resolve a fallback URL instead.
If that fails too, the exception is thrown.
'fallback_locale' => 'en',Specify your main locale if you want to omit its slug from the URL:
'omitted_locale' => 'en',This option has no effect if you use domains instead of slugs.
To set an option for one localized route group only, you can specify it as the second parameter of the localized route macro. This will override the config file settings. Currently, only 2 options can be overridden.
Route::localized(function () {
Route::get('about', [AboutController::class, 'index']);
}, [
'supported_locales' => ['en', 'nl', 'fr'],
'omitted_locale' => 'en',
]);By default, the app locale will always be what you configured in config/app.php.
To automatically update the app locale, you need to register the middleware in the web middleware group.
Make sure to add it after StartSession and before SubstituteBindings.
The order of the middleware is important if you are using localized route keys (translated slugs)! The session needs to be active when setting the locale, and the locale needs to be set when substituting the route bindings.
Add the middleware to the web middleware group in bootstrap/app.php.
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->web(remove: [
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);
$middleware->web(append: [
\CodeZero\LocalizedRoutes\Middleware\SetLocale::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);
})Add the middleware to the web middleware group in app/Http/Kernel.php.
…php Route::localized(function () { Route::get('about', [AboutController::class, 'index'])->name('about'); });
…php // Example: use the post slug as the route parameter Route::get('posts/{post:slug}', [PostsController::class, 'index']);
// PostsController.php public function index(Post $post) { return $post; }
However, to resolve a localized parameter you need to add a `resolveRouteBinding()` method to your model.
In this method you need to write the logic required to find a match, using the parameter value from the URL.
For example, you might have a JSON column in your database containing translated slugs:
```php
public function resolveRouteBinding($value, $field = null)
{
// Default field to query if no parameter field is specified
$field = $field ?: $this->getRouteKeyName();
// If the parameter field is 'slug',
// lets query a JSON field with translations
if ($field === 'slug') {
$field .= '->' . App::getLocale();
}
// Perform the query to find the parameter value in the database
return $this->where($field, $value)->firstOrFail();
}
…
php
lang/nl/routes.php
lang/fr/routes.phpThen you add the appropriate translations to each file:
// lang/nl/routes.php
return [
'about' => 'over',
'us' => 'ons',
];And finally, you use the macro when registering routes:
Route::localized(function () {
Route::get(Lang::uri('about/us'), [AboutController::class, 'index'])->name('about');
});The URI macro accepts 2 additional parameters:
Lang::uri('hello/world', 'fr', 'my-package');You can also use trans()->uri('hello/world') instead of Lang::uri('hello/world').
Using these example translations:
// lang/nl/routes.php
return [
'hello' => 'hallo',
'world' => 'wereld',
'override/hello/world' => 'something/very/different',
'hello/world/{parameter}' => 'uri/with/{parameter}',
];These are possible translation results:
// Translate every slug individually
// Translates to: 'hallo/wereld'
Lang::uri('hello/world');
// Keep original slug when missing translation
// Translates to: 'hallo/big/wereld'
Lang::uri('hello/big/world');
// Translate slugs, but not parameter placeholders
// Translates to: 'hallo/{world}'
Lang::uri('hello/{world}');
// Translate full URIs if an exact translation exists
// Translates to: 'something/very/different'
Lang::uri('override/hello/world');
// Translate full URIs if an exact translation exists (with placeholder)
// Translates to: 'uri/with/{parameter}'
Lang::uri('hello/world/{parameter}');A standard 404 response has no actual Route and does not go through the middleware.
This means our middleware will not be able to update the locale and the request can not be localized.
To fix this, you can register this fallback route at the end of your routes/web.php file:
Route::fallback(\CodeZero\LocalizedRoutes\Controllers\FallbackController::class);
…
bash
php artisan route:cacheYou can get the URL of your named routes as usual, using the route() helper.
$url = route('about'); If you registered an about route that is not localized, then about is an existing route name and its URL will be returned.
Otherwise, this will try to generate the about URL for the active locale, e.g. en.about.
In some cases, you might need to generate a URL for a specific locale.
For this purpose, an additional locale parameter was added to Laravel's route() helper.
$url = route('about', [], true, 'nl'); // this will load 'nl.about'There are a number of ways to generate route URLs with localized parameters.
Let's say we have a Post model with a getSlug() method:
public function getSlug($locale = null)
{
$locale = $locale ?: App::getLocale();
$slugs = [
'en' => 'en-slug',
'nl' => 'nl-slug',
];
return $slugs[$locale] ?? '';
}Of course, in a real project the slugs wouldn't be hard-coded. If you are looking for a good solution to implement translated attributes on your models, be sure to check out spatie/laravel-translatable.
Now you can pass a localized slug to the route() function:
route('posts.show', [$post->getSlug()]);
route('posts.show', [$post->getSlug('nl')], true, 'nl');You can let Laravel resolve localized parameters automatically by adding the getRouteKey() method to your model:
public function getRouteKey()
{
$locale = App::getLocale();
$slugs = [
'en' => 'en-slug',
'nl' => 'nl-slug',
];
return $slugs[$locale] ?? '';
}Now you can just pass the model:
route('posts.show', [$post]);
route('posts.show', [$post], true, 'nl');A fallback locale can be provided in the config file.
If the locale parameter for the route() helper is not a supported locale, the fallback locale will be used instead.
// When the fallback locale is set to 'en'
// and the supported locales are 'en' and 'nl'
$url = route('about', [], true, 'nl'); // this will load 'nl.about'
$url = route('about', [], true, 'wk'); // this will load 'en.about'If neither a regular nor a localized route can be resolved, a Symfony\Component\Routing\Exception\RouteNotFoundException will be thrown.
To generate a URL for the current route in any locale, you can use the Route::localizedUrl() macro.
Just like with the route() helper, you can pass parameters as a second argument.
Let's say we have a Post model with a getSlug() method:
public function getSlug($locale = null)
{
$locale = $locale ?: App::getLocale();
$slugs = [
'en' => 'en-slug',
'nl' => 'nl-slug',
];
return $slugs[$locale] ?? '';
}Now you can pass a localized slug to the macro:
$current = Route::localizedUrl(null, [$post->getSlug()]);
$en = Route::localizedUrl('en', [$post->getSlug('en')]);
$nl = Route::localizedUrl('nl', [$post->getSlug('nl')]);If you add the model's getRouteKey() method, you don't need
暂无开放 Issues,或尚未同步最近议题。