Laravel 5.4:如何在控制器中不使用route参数 [英] Laravel 5.4: How to DO NOT use route parameter in controller
问题描述
我正在开发一种多语言应用程序,并试图制作一个中间件以将路由{locale}前缀传递给URL.但是现在我不需要在控制器中使用此{locale}参数,例如:
I am developing a Multilingual application and trying to make a middleware to pass route {locale} prefix to URL. But now I do not need to use this {locale} parameter in controller, for example:
public function getPost(App\Post $post)
{
return view('welcome')->withPost($post);
}
但是,除非我将App\Post $post
更改为$locale, App\Post $post
,否则上面的代码不起作用.
But the code above does not work unless I change the App\Post $post
to $locale, App\Post $post
.
问题是因为每当我创建一个新的控制器时,我都需要传递$ locale参数.那不酷.
The problem is because I'll need to pass the $locale parameter whenever I create a new controller. That is not cool.
如何避免将$locale
参数传递给所有控制器?我不需要它,因为我已经在中间件上使用它了.
How to avoid passing $locale
parameter to all controllers? I do not need it because I already used it on my middleware.
更新:
routes \ web.php
routes\web.php
Route::prefix('{locale}')->middleware('locale')->group(function () {
Route::get('/', 'PageController@getHome')->name('welcome');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
...
// This route must be the last!
Route::get('/{post}', 'PageController@getPost')->name('post');
});
推荐答案
我不使用前缀参数而是使用自定义辅助函数解决了我的问题.
I solved my question without using a prefix parameter, but using a custom helper function.
通过这种方式,我不再需要中间件来解析{locale}前缀参数.请参阅我的自定义帮助程序函数,以从URL解析语言环境:
By this way, I do not need a middleware to parse the {locale} prefix parameter anymore. See my custom helper function to parse locale from URL:
function parseLocale()
{
$locale = Request::segment(1);
$languages = ['pt', 'it', 'fr', 'ru', 'es'];
if (in_array($locale, $languages)) {
App::setLocale($locale);
return $locale;
}
return '/';
}
现在我只需要在Route :: prefix()上使用它,如下所示:
Now I need just to use it on my Route::prefix() like following:
Route::prefix(parseLocale())->group(function () {
Auth::routes();
Route::get('home', 'HomeController@index')->name('home');
Route::get('/', 'PageController@getHome')->name('welcome');
...
如您所见,如果您尝试导航至www.site.com/pt/something
,则应用程序将为您提供something
路由,就像您尝试导航至www.site.com/something
一样.但是,如果没有语言环境前缀,Laravel将加载您在config\app.php
中设置的默认语言.
As you can see, if you try to navigate into www.site.com/pt/something
the application will give you the something
route the same way you try to navigate into www.site.com/something
. But without the locale prefix the Laravel will load the default language you've set in config\app.php
.
谢谢你们!
这篇关于Laravel 5.4:如何在控制器中不使用route参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!