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

标签 php laravel laravel-5 laravel-5.5

目前我的 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/

相关文章:

php - java脚本对象数组通过ajax(jquery)和json到php

php - Laravel Bootstrap 4 Modal - 在带有 AJAX 调用数据的点击事件上显示模态

php - Laravel 5.4 多重身份验证 - Auth::guard()->user() 空

在 Laravel 中安装 Dompdf 后出现 PHP 错误

php - Kubernetes和PHP-FPM具有多个环境,环境变量问题

php - 如何根据 laravel 5.4 上博客文章的 user_id 显示用户名?

php - Android 和 PHP 连接到 MySQL 数据库

php - 如何使用数组中的值通过2行比较来选择mysql中的表?

php - 提高CPU密集型PHP脚本的性能

php - Laravel 迁移 : 2 different tables with the same blueprint/structure