laravel路由沒法訪問,報404,No query results for model [App\Models\...]

今天遇到了一個問題,在routes/web.php中配置了路由,但始終沒法訪問該路由,一直報404。php

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

而後我在app/Exceptions/Handler.php文件中,修改render()方法:laravel

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

把異常打印出來:web

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

先經過 php artisan route:list 查看路由列表app

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

緣由是laravel路由訪問檢測是從上到下的。blog

針對同路徑,gift_packs/{gift_pack} 和 gift_packs/test,當咱們訪問 /gift_packs/test時,路由 gift_packs/{gift_pack} 已經解析了。路由

字符串 'test' 沒法獲取GiftPack模型數據,因此就報錯了。字符串

解決方法是修改路由配置的上下位置:get

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

這樣就能夠了。it

相關文章
相關標籤/搜索