如何在获取路由中将默认参数传递给 Laravel 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34362340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:50:03  来源:igfitidea点击:

How to pass default parameters to laravel controller in a get route

laravellaravel-4laravel-routing

提问by horse

I have a route like that:

我有一条这样的路线:

Route::get('category/{id}/{date?}', array('as' => 'category/date', 'uses' => 'Controller@getCategory'));

I want to run @getCategory with default parameters when called '/' root route. So if '/' route called, getCategory function should run with id=1 and date=2015-12-18.

我想在调用“/”根路由时使用默认参数运行 @getCategory。因此,如果调用“/”路由,则 getCategory 函数应以 id=1 和 date=2015-12-18 运行。

How should I do that?

我该怎么做?

回答by Joseph Silber

Register it as a separate route:

将其注册为单独的路由:

Route::get('/', 'Controller@getCategory')->named('home');
Route::get('category/{id}/{date?}', 'Controller@getCategory')->named('category/date');

Then in your controller, set default values for those arguments:

然后在您的控制器中,为这些参数设置默认值:

public function getCategory($id = 1, $date = '2015-12-18')
{
    // do your magic...
}

回答by Unai Susperregi

It works for me with a "?" {date?}in the route, and putting a default value in the anonimus function.$date = null

它适用于我"?" {date?}路线中使用 a并在anonimus 函数中放置一个默认值。$date = null

Route

路线

Route::get('category/{id}/{date?}', function($date = null) {
   if ($date === null)
      //Option 1
   else
      //Option 2    
});