簡體   English   中英

用於路由的Builder.php中的Laravel 5 ModelNotFoundException

[英]Laravel 5 ModelNotFoundException in Builder.php for Routing

我有一個名為Article.php的Model Class,並使用下面的rout:

Route::get('articles/create','ArticlesController@create');

當在瀏覽器中輸入http:// localhost:8000 / articles / create時,我看到此錯誤: Builder.php第125行中的ModelNotFoundException:模型[App \\ Article]沒有查詢結果。

但是當我用戶下面的每一個想法都沒問題時:(文章放入文章s

Route::get('article/create','ArticlesController@create');

這是我的控制器:

class ArticlesController extends Controller {

    public function index()
    {
        $articles = Article::all();

        return view('articles.index',compact('articles'));
    }


    public function show($id)
    {
        $article = Article::findOrFail($id);

        return view('articles.show',compact('article'));
    }

    public function create()
    {
        return view('articles.create');
    }
}

真的發生了什么?!!!

你的代碼的問題是你的routes.php你的路由優先級是這樣的:

Route::get('articles/{id}','ArticlesController@show');
Route::get('articles/create','ArticlesController@create');

當您在瀏覽器中轉到http:// localhost:8000 / articles / create時 ,laravel catch會在articles/create獲得解析路徑的機會之前,在articles/{id} articles/create帶有{id}請求的變量。 要解決您的問題,您必須考慮路由優先級並對route.php文件進行以下更改:

Route::get('articles/create','ArticlesController@create');
Route::get('articles/{id}/edit','ArticlesController@show');
Route::get('articles/{id}','ArticlesController@show');

但是如果你在routes.php文件中有很多這些,你應該考慮使用它:

Route::resource('articles', 'ArticlesController');

這一行將處理所有4個獲取路由(索引,創建,編輯,顯示)以及(存儲,更新,刪除)的所有三個發布/放置/刪除路由。

但是每個人都有自己的。

您應該包含您的控制器代碼。

很可能那里有一些代碼在Eloquent模型上嘗試findOrFail(),觸發了這個錯誤。

我發現了一個問題:在Rout.php中我有以下代碼:

Route::get('articles/{id}','ArticlesController@show');
Route::get('articles/create','ArticlesController@create');

當我在瀏覽器中使用http:// localhost:8000 / articles / create時 ,將pass創建為'article / {id}'並使用第一個Rout然后轉到ArticlesController @ show並將'create'改為id作為show method參數。 然后找不到具有id = create和返回異常的文章;

解決問題必須改變路由序列,如下所示:

Route::get('articles/create','ArticlesController@create');
Route::get('articles/{id}','ArticlesController@show');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM