Routing Laravel(5)-通过可选参数路由到控制器
我想创建一个路由,它需要一个必需的ID和可选的开始和结束日期(“Ymd”)。如果省略日期,则返回默认值。(比如说最后30天)打电话给管制员……比如说path@index"Routing Laravel(5)-通过可选参数路由到控制器,routing,laravel-5,Routing,Laravel 5,我想创建一个路由,它需要一个必需的ID和可选的开始和结束日期(“Ymd”)。如果省略日期,则返回默认值。(比如说最后30天)打电话给管制员……比如说path@index" Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null) { if(!$start) { //set start } if(!$end) { //set e
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path@index' with $id, $start, and $end?
});
任何帮助都将不胜感激。我肯定有一个简单的答案,但我在任何地方都找不到
提前感谢您的帮助 无法从
路由调用控制器::get
closure
使用Route::get('/path/{id}/{start?}/{end?}','Controller@index');编码>并处理控制器功能中的参数:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
我会用三条路径来处理它:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
注意顺序-您希望首先检查完整路径
您可以从路由关闭调用控制器操作,如下所示:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
我所做的是将可选参数设置为query参数,如下所示:
示例URL:
/getStuff/2019-08-27?type=0&color=red
路线:
Route::get('/getStuff/{date}','Stuff\StuffController@getStuff');代码>
控制器:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
这帮助我简化了可选路线参数(来自Laravel文档):
有时您可能需要指定管线参数,但该管线参数的存在是可选的。您可以通过放置?在参数名称后标记。确保为路由的相应变量指定默认值:
或者,如果在路由中有控制器调用操作,则可以执行以下操作:
web.php
Route::get('user/{name?}', 'UsersController@index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
我希望这能像我一样帮助别人简化可选参数
在此处查找更多详细信息(Laravel 7):如果发送了两个参数中的一个,是否会将其设置为$start,因为这是路由中定义的第一个参数?这里唯一的问题是:route::get('/path/{id}/{end},…);因为已经定义了此路由:route::get('/path/{id}/{start},…);有趣的是,从功能上讲,如果只提供一个日期,代码将无法知道这是结束日期还是开始日期。程序员将不得不决定它应该是哪个。你完全正确。:)我读了更多关于这方面的内容,并且理解了当它们是多个可选参数时,您总是需要设置前面的参数,以便将以下参数考虑在内。这有效地使你的三条路线正确无误。@Michael Pittino的答案是最好的实践方法,这可能是一个解决方案,但不是一个完美的解决方案。
web.php
Route::get('user/{name?}', 'UsersController@index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
Route::get('user/{name?}', function ($name = null) {
return $name;
});