【问题标题】:Change route group prefix when changed locale更改区域设置时更改路由组前缀
【发布时间】:2019-09-13 14:40:32
【问题描述】:

我想在更改语言环境时更改路由组前缀。

例如,如果语言环境是 en:

     Route::group(['prefix' => 'giveaway'], function () {

     });

如果语言环境是 tr:

     Route::group(['prefix' => 'cekilis'], function () {

     });

我该怎么做。

我试过了

   'prefix'=>__('routes.prefix')

但应用无法访问路线中的当前语言环境。

【问题讨论】:

    标签: php laravel routes localization


    【解决方案1】:

    我建议您使用中间件将语言环境设置为动态

    创建一个中间件,如下所示:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class Language
    {
        /**
        * Handle an incoming request.
        *
        * @param  \Illuminate\Http\Request  $request
        * @param  \Closure  $next
        * @return mixed
        */
        public function handle($request, Closure $next)
        {
            \App::setLocale($request->locale);
    
            return $next($request);
        }
    }
    

    并在 app\Http\Kernel 中注册这个中间件:

    protected $middlewareGroups = [
        'web' => [
                // ...
                \App\Http\Middleware\Language::class,
                // ...
        ]
    ];
    

    最后你可以在你的路由文件上调用你的中间件

    Route::middleware('language')->group(function ($locale) {
    
        //You have a condition as you wish
    
        if ($locale == 'en') {
            Route::group(['prefix' => 'giveaway'], function () {
            .......
    
            });
        } elseif ($locale == 'tr') {
            Route::group(['prefix' => 'cekilis'], function () {
            ........
    
            });
        }
    
    });
    

    希望能解决你的问题

    【讨论】:

    • 感谢您的推荐。我试试这个,但不起作用。我在小组中写了一些路线,例如; ` Route::get('/', function ($locale) { return 'asd'; })->name("d.test"); ` 但错误是“Route [d.test] not defined”
    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多