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


今天遇到了一個問題,在routes/web.php中配置了路由,但始終無法訪問該路由,一直報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');

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

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

把異常打印出來:

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

先通過 php artisan route: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                 | 

原因是laravel路由訪問檢測是從上到下的。

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

字符串 'test' 無法獲取GiftPack模型數據,所以就報錯了。

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

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

這樣就可以了。

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM