Laravel (5) - Маршрутизация контроллера с дополнительными параметрами
Я хотел бы создать маршрут с требуемым идентификатором и необязательными датами начала и окончания ( "Ymd" ). Если даты опущены, они возвращаются к умолчанию. (Скажите последние 30 дней) и вызовите контроллер.... позволяет сказать "path @index"
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 '[email protected]' with $id, $start, and $end?
});
Любая помощь будет оценена по достоинству. Я уверен, что есть простой ответ, но я ничего не мог найти.
Заранее благодарим за помощь!
Ответы
Ответ 1
Невозможно вызвать контроллер из замыкания Route:::get
.
Используйте Route::get('/path/{id}/{start?}/{end?}', '[email protected]');
и обработайте параметры в функции контроллера:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
Ответ 2
Я бы справился с тремя путями:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Обратите внимание на порядок - сначала вы хотите проверить полный путь.
Ответ 3
Вы можете вызвать действие контроллера из закрытия маршрута следующим образом:
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;
});
Ответ 4
Я установил необязательные параметры как параметры запроса, например:
Пример URL:
/getStuff/2019-08-27?type=0&color=red
Маршрут:
Route::get('/getStuff/{date}','Stuff\[email protected]');
Контроллер:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}