Search code examples
laravellaravel-routing

Laravel route issue: "No query results for model"


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.


Solution

  • 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.