Tag Archives: 404No query results for model [App\Models\…]

Laravel route cannot be accessed, report 404, no query results for model

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

Today, we encountered a problem. We configured the route in routes/web.php, but we were unable to access the route. We kept reporting 404

Route::resource('gift_packs', 'GiftPacksController', ['only' => ['index', 'show', 'create', 'store', 'update', 'edit', 'destroy']]);
Route::get('gift_packs/test', 'GiftPacksController@test')->name('gift_packs.test');

Then I modify the render () method in the app/exceptions/handler.php file

public function render($request, Exception $exception)
{
    dd($exception);
    return parent::render($request, $exception);
}

Print out the exception:

No query results for model [App\Models\GiftPack].

First, through PHP artisan route:list View routing list

| Domain | Method                                 | URI                                                   | Name                            | 
|        | GET|HEAD                               | gift_packs/{gift_pack}                                | gift_packs.show                 | 
|        | DELETE                                 | gift_packs/{gift_pack}                                | gift_packs.destroy              | 
|        | PUT|PATCH                              | gift_packs/{gift_pack}                                | gift_packs.update               | 
|        | GET|HEAD                               | gift_packs/{gift_pack}/edit                           | gift_packs.edit                 | 
|        | GET|HEAD                               | gift_packs/test                                       | gift_packs.test                 |

The reason is that laravel routing access detection is from top to bottom

For the same path, gift_ packs/{gift_ Pack} and gift_ Pack/test, when we visit/Gift_ When packages/test, route gift_ packs/{gift_ Pack} has been parsed

The string ‘test’ could not get the data of the Giftpack model, so an error was reported

The solution is to modify the location of the routing configuration

Route::get('gift_packs/test', 'GiftPacksController@test')->name('gift_packs.test');
Route::resource('gift_packs', 'GiftPacksController', ['only' => ['index', 'show', 'create', 'store', 'update', 'edit', 'destroy']]);

That’s it