简体   繁体   中英

default value for route parameter in Laravel

Hi My website must be multi-lang and everything are OK except one piece for example my homepage route is like below:

Route::get('/{lang}','Welcomecontroller@index');

and in AppServiceProvider in boot method I write function that came in following:

public function boot()
{
 $request=Request::capture();
 Cookie::queue('lang',$request->lang);
 $lang=$request->has('lang') ? $request->lang : "fa";
 app()->setLocale($lang);
}

problem of my code is here,my code works fine when pass query string like ?lang=en but in passing parameter in route like get('/{lang}','WelcomeController@index'); if parameter is not exist 404 page showing and always showing fa lang if parameter pass. Is there any way to this method if {lang} parameter isn't exist by default showing for example en lang and url showing just like http://localhost:8000/ against http://localhost:8000/en and how get {lang} parameter from url in that method.

You can make it nullable like that

Route::get('/{lang?}','Welcomecontroller@index');

And inside your controller Welcomecontroller in index function you can pass default value like that:

public function index($lang = 'fa'){
// code
}

you can get more information from https://laravel.com/docs/6.x/routing#parameters-optional-parameters

you can use URL::defaults. also you can get your answer from https://laravel.com/docs/5.6/urls#default-values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM