百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
L

laravel-localized-routes

> 后端框架
开源

⭐️ 在 Laravel 应用中设置和使用本地化路由的便捷方式。

544 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

⭐️ 在 Laravel 应用中设置和使用本地化路由的便捷方式。

Laravel Localized Routes

A convenient way to set up and use localized routes in a Laravel app.

Table of Contents

  • Requirements
  • Upgrade
  • Install
  • Configure
    • Publish Configuration File
    • Configure Supported Locales
      • Simple Locales
      • Custom Slugs
      • Custom Domains
    • Use Fallback Locale
    • Omit Slug for Main Locale
    • Scoped Options
  • Add Middleware to Update App Locale
    • Detectors
    • Stores
  • Register Routes
    • Translate Parameters with Route Model Binding
    • Translate Hard-Coded URI Slugs
  • Localize 404 Pages
  • Cache Routes
  • Generate Route URLs
    • Generate URLs for the Active Locale
    • Generate URLs for a Specific Locale
    • Generate URLs with Localized Parameters
    • Fallback URLs
    • Generate Localized Versions of the Current URL
    • Example Locale Switcher
  • Generate Signed Route URLs
  • Redirect to Routes
  • Automatically Redirect to Localized URLs
  • Helpers
  • Testing
  • Credits
  • Security
  • Changelog
  • License

✅ Requirements

  • PHP >= 8.1
  • Laravel >= 10
  • Composer ^2.3 (for codezero/composer-preload-files)

⬆ Upgrade

Upgrading to a new major version? Check our upgrade guide for instructions.

Install

Install this package with Composer:

bash
composer require codezero/laravel-localized-routes

Laravel will automatically register the ServiceProvider.

⚙ Configure

☑ Publish Configuration File

bash
php artisan vendor:publish --provider="CodeZero\LocalizedRoutes\LocalizedRoutesServiceProvider" --tag="config"

You will now find a localized-routes.php file in the config folder.

☑ Configure Supported Locales

Simple Locales

Add any locales you wish to support to your published config/localized-routes.php file:

php
'supported_locales' => ['en', 'nl'];

These locales will be used as a slug, prepended to the URL of your localized routes.

Custom Slugs

You can also use a custom slug for a locale:

php
'supported_locales' => [
    'en' => 'english-slug',
    'nl' => 'dutch-slug',
];

Custom Domains

Or you can use a custom domain for a locale:

php
'supported_locales' => [
    'en' => 'english-domain.test',
    'nl' => 'dutch-domain.test',
];

☑ Use Fallback Locale

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.

php
'fallback_locale' => 'en',

☑ Omit Slug for Main Locale

Specify your main locale if you want to omit its slug from the URL:

php
'omitted_locale' => 'en',

This option has no effect if you use domains instead of slugs.

☑ Scoped Options

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.

php
Route::localized(function () {
    Route::get('about', [AboutController::class, 'index']);
}, [
    'supported_locales' => ['en', 'nl', 'fr'],
    'omitted_locale' => 'en',
]);

Add Middleware to Update App Locale

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.

Laravel 11 and newer:

Add the middleware to the web middleware group in bootstrap/app.php.

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,
    ]);
})

Laravel 10:

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.php

Then you add the appropriate translations to each file:

php
// lang/nl/routes.php
return [
    'about' => 'over',
    'us' => 'ons',
];

And finally, you use the macro when registering routes:

php
Route::localized(function () {
    Route::get(Lang::uri('about/us'), [AboutController::class, 'index'])->name('about');
});

The URI macro accepts 2 additional parameters:

  1. A locale, in case you need translations to a locale other than the current app locale.
  2. A namespace, in case your translation files reside in a package.
php
Lang::uri('hello/world', 'fr', 'my-package');

You can also use trans()->uri('hello/world') instead of Lang::uri('hello/world').

Example

Using these example translations:

php
// 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:

php
// 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}');

Localize 404 Pages

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:

php
Route::fallback(\CodeZero\LocalizedRoutes\Controllers\FallbackController::class);

…

bash
php artisan route:cache

⚓ Generate Route URLs

☑ Generate URLs for the Active Locale

You can get the URL of your named routes as usual, using the route() helper.

php
$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.

☑ Generate URLs for a Specific Locale

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.

php
$url = route('about', [], true, 'nl'); // this will load 'nl.about'

☑ Generate URLs with Localized Parameters

There are a number of ways to generate route URLs with localized parameters.

Pass Localized Parameters Manually

Let's say we have a Post model with a getSlug() method:

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

php
route('posts.show', [$post->getSlug()]);
route('posts.show', [$post->getSlug('nl')], true, 'nl');

Use a Custom Localized Route Key

You can let Laravel resolve localized parameters automatically by adding the getRouteKey() method to your model:

php
public function getRouteKey()
{
    $locale = App::getLocale();
    
    $slugs = [
        'en' => 'en-slug',
        'nl' => 'nl-slug',
    ];

    return $slugs[$locale] ?? '';
}

Now you can just pass the model:

php
route('posts.show', [$post]);
route('posts.show', [$post], true, 'nl');

☑ Fallback URLs

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.

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

☑ Generate Localized Versions of the Current URL

To generate a URL for the current route in any locale, you can use the Route::localizedUrl() macro.

Pass Parameters Manually

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:

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

php
$current = Route::localizedUrl(null, [$post->getSlug()]);
$en = Route::localizedUrl('en', [$post->getSlug('en')]);
$nl = Route::localizedUrl('nl', [$post->getSlug('nl')]);

Use a Custom Route Key

If you add the model's getRouteKey() method, you don't need

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPcountrylanguagelaravellocale

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架