目前我的 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' );
} );
这并没有真正起到应有的作用。
我想要的是这样的 url:
/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
所以我希望 locale 参数在 url 的开头是可选的。
到目前为止,我已经设法实现的只是在自己指定语言环境时让 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
}
但我认为这是一个但意味着我必须在每个 Controller 中设置默认语言环境,这在我看来有点难看。此外,我认为这应该可以在 Laravel 中以更优雅的方式实现。
如何为我的 url 中的 locale
前缀设置默认值?
最佳答案
你必须深入思考生成的路由。并且永远不要使用前缀作为可选,所以为了使所有 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 );
关于php - Laravel 5.5 语言环境作为 url 中的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48565900/