问题
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);
}
But the code above does not work unless I change the App\Post $post
to $locale, App\Post $post
.
The problem is because I'll need to pass the $locale parameter whenever I create a new controller. That is not cool.
How to avoid passing $locale
parameter to all controllers? I do not need it because I already used it on my middleware.
UPDATE:
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');
});
回答1:
There is a forgetParameter()-method in Laravel's route class, that can remove a parameter from being parsed to controller methods.
It can be used e.g. in a middleware, by calling it like so:
$request->route()->forgetParameter('locale');
Then the parameter will be removed from the controller dispatcher's parameter property and thereby not get parsed on to the controller methods as parameter.
回答2:
I solved my question without using a prefix parameter, but using a custom helper function.
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 '/';
}
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');
...
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
.
Thank you guys!
回答3:
Remove {locale}
from your route parameters if it is not needed. It sounds like you still have the routes defined with it in there. Please post your routes/web.php
so we can verify.
If your route is defined like:
Route::get('/{locale}/{post}', 'PostController@getPost');
Laravel will expect 2 parameters and bind whatever is in place for the first one. So for example, '/some-post'
would bind 'some-post'
to {locale}
and still expect another route parameter for {post}
来源:https://stackoverflow.com/questions/44619512/laravel-5-4-how-to-do-not-use-route-parameter-in-controller