目前我在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工作。当我不手动指定区域设置时,我总是收到not found
消息。
我知道我应该能够这样做:
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中以更优雅的方式实现。
如何在我的网址中设置locale
前缀的默认值?
答案 0 :(得分:4)
您必须考虑深度生成的路线。并且从不使用前缀作为可选,因此要使工作所有网址都在这样的路线中进行更改
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 );