Reputation: 59
I'm pretty confused about how ROUTE works in these cases.
I have defined such a combination of routes:
Route::apiResource('users', 'UserController');
Route::get('users/{user}/tasks', 'UserController@tasks');
And everything is fine. No issue. But
I did the same for the other Model:
Route::apiResource('tasks', 'TaskController');
Route::get('tasks/calendar', 'TaskController@calendar');
And for this combination I got the NotFoundHttpException :/
{
"message": "No query results for model [App\\Models\\Task] calendar",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", ...
If I change in URI e.g 'task/calendar' then it works. What I'm missing?
Thanks for help.
Upvotes: 2
Views: 1262
Reputation: 565
Because you are using Route::resource
(or alternatively Route::apiResource
), GET
calls with the format tasks/{task_id}/anything
or tasks/anything
are getting routed to the show()
controller method.
In my opinion, moving other GET
routes above Route::resource
smells hacky and is sloppy practice.
A more elegant solution is just to add another path to the route (such as /list
), so that show()
does not grab that route.
Route::apiResource('tasks', 'TaskController');
Route::get('tasks/list/calendar', 'TaskController@calendar');
Route::get('tasks/list/tasks', 'TaskController@tasks');
Upvotes: 0
Reputation: 5802
The
Route::get('tasks/calendar', 'TaskController@calendar');
has to be moved above:
Route::apiResource('tasks', 'TaskController');
to work because the apiResource
exposes the tasks/{task}
route that matches before it reaches the tasks/calendar
route.
The order doesn't cause an issue for Users route:
Route::get('users/{user}/tasks', 'UserController@tasks');
because it has a extra url segment(/tasks
) that prevents it from clashing with users/{user}
.
Checkout your current routes using php artisan route:list
.
Upvotes: 3