php – Laravel 5.5语言环境作为url中的前缀

目前我在我的routes / web.PHP中有以下内容

Route::group( [ 'prefix' => '{locale?}', 'middleware' =>\App\Http\Middleware\Locale::class ], function (\Illuminate\Routing\Router $router) {

    Route::get( '/', 'LandingController@index' )->name( 'home' );
    Route::get( '/hero/create', 'HeroController@create' )->name( 'hero.create' );
} );

这并没有真正起作用.

我想要的是这样的网址:

/create/hero    # should work with the default locale
/fr/create/hero # should use the french locale
/nl/create/hero # should use dutch locale
/               # should work with the default locale
/fr             # should use the french locale
/nl             # should use dutch locale

所以我希望在url的开头可以选择locale参数.
到目前为止,我设法实现的只是在自己指定语言环境时让URL工作.当我不手动指定语言环境时,我总是收到一条未找到的消息.

我知道我应该能够这样做:

Route::get('/path/{id}/{start?}/{end?}', ['as' => 'route.name', 'uses' => 'PathController@index']);

public function index($id, $start = "2015-04-01", $end = "2015-04-30")
{
    // code here
}

但我认为这是一个但意味着我必须在每个控制器中设置认语言环境,这在我看来有点难看.此外,我认为这应该可以在Laravel中以更优雅的方式实现.

如何在我的网址中设置区域设置前缀的认值?

解决方法:

你必须考虑深入生成的路线.并且永远不要使用前缀作为可选项,因此要使工作所有url在这样的路由中进行更改

Route::get( '/', 'LandingController@index' )->name( 'home' );
Route::get( '/hero/create', 'HeroController@create' )->name( 'hero.create' );

Route::group( [ 'prefix' => '{locale}', 'middleware' =>\App\Http\Middleware\Locale::class ], function (\Illuminate\Routing\Router $router) {
    Route::get( '/', 'LandingController@index' )->name( 'home' );
    Route::get( '/hero/create', 'HeroController@create' )->name( 'hero.create' );
} );

以下是您的简短说明

/               # should work with first above route 
/create/hero    # should work with first above route
/fr/create/hero # should work with route inside prefix
/nl/create/hero # should work with route inside prefix
/fr             # should work with route inside prefix
/nl             # should work with route inside prefix

它可以解决将可选({locale?})放在最后一个不在中间,或者你可以将路由放入一个变量并放入两个条件,我的意思是外部前缀和内部前缀.

$heroRoutes = function (\Illuminate\Routing\Router $router) {
    Route::get( '/', 'LandingController@index' )->name( 'home' );
    Route::get( '/hero/create', 'HeroController@create' )->name( 'hero.create' );
}
Route::group( [ 'middleware' =>\App\Http\Middleware\Locale::class ], $heroRoutes );
Route::group( [ 'prefix' => '{locale}', 'middleware' =>\App\Http\Middleware\Locale::class ], $heroRoutes );

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...