Php 带有Route::group、前缀和命名空间的Laravel本地化

Php 带有Route::group、前缀和命名空间的Laravel本地化,php,laravel,localization,Php,Laravel,Localization,“您也可以在运行时使用App facade上的setLocale方法更改活动语言:” 如果我们有这样的东西,我们如何使用$locale实现这一点: Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function( $locale ) { // this does not work. App::setLocale( $locale ); // this do

“您也可以在运行时使用App facade上的setLocale方法更改活动语言:”

如果我们有这样的东西,我们如何使用$locale实现这一点:

Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function( $locale ) {
    // this does not work.
    App::setLocale( $locale );

    // this does work.
    App::setLocale( Request::segment( 3 ) );

    Route::resource('product', 'ProductController', ['except' => [
        'show'
    ]]);

});

问题在于路线参数,而不是本地化

因为您希望路由有两个参数,所以应该为闭包传递两个参数

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) { 
    // 
});
在你的例子中

Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function( $id, $locale ) { 
    // this does not work.
    App::setLocale( $locale ); 
    // this does work.
    App::setLocale( Request::segment( 3 ) );
    Route::resource('product', 'ProductController', ['except' => [ 'show' ]]);
});

有关更多信息,请参见-
Route::group
callback会在任何请求时执行(即使不是您的前缀!)
Route::group
Route::get/post/match
不同,它类似于内部get/post/match调用的助手

App::setLocale($locale)不起作用,因为
Laravel
只将
lighting\Routing\Router
的实例传递到组的回调中。在此阶段,
locale
前缀尚未提取,甚至URL也未处理

App::setLocale(请求::段(3))将针对“一/二/三”执行,区域设置为“三”

你的例子应该是:

Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function() {
    // test a locale
    Route::get('test', function($locale){ echo $locale; });

    // ProductController::index($locale)
    Route::resource('product', 'ProductController', ['except' => [
        'show'
    ]]);
});
因此,只需更新ProductController并添加$locale作为参数

备选方案:如果您希望在一个地方设置语言环境,请更新您的路线:

// set locale for '/admin/anything/[en|fr|ru|jp]/anything' only
if (Request::segment(1) === 'admin' && in_array(Request::segment(3), ['en', 'fr', 'ru', 'jp'])) {
    App::setLocale(Request::segment(3));
} else {
    // set default / fallback locale
    App::setLocale('en');
}

Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function() {
    Route::resource('product', 'ProductController', ['except' => [
        'show'
    ]]);
});

问题在于路线参数的数量。参考下面我的答案。我已经试过了。App\Providers\RouteServiceProvider::{closure}()缺少参数2
// set locale for '/admin/anything/[en|fr|ru|jp]/anything' only
if (Request::segment(1) === 'admin' && in_array(Request::segment(3), ['en', 'fr', 'ru', 'jp'])) {
    App::setLocale(Request::segment(3));
} else {
    // set default / fallback locale
    App::setLocale('en');
}

Route::group(['prefix' => 'admin/{id}/{locale}', 'namespace' => 'Admin'], function() {
    Route::resource('product', 'ProductController', ['except' => [
        'show'
    ]]);
});