Laravel 5 ModelNotFoundException in Builder.php for Routing



我有一个名为 Article 的模型类.php并使用以下路由:

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

在浏览器中输入时 http://localhost:8000/articles/create我看到此错误:生成器中的 ModelNotFoundException.php第 125 行:模型 [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');
    }
}

发生的事情真的很?!!!

代码的问题在于,在您的路由中.php路由优先级如下所示:

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

当您在浏览器中转到 http://localhost:8000/articles/create 时,Laravel会捕获创建为变量{id}并在articles/{id}中请求articles/create然后才有机会解析路由。要解决您的问题,您必须考虑路由优先级并对路由.php文件进行以下更改:

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

但是,如果您的路由.php文件中有一堆这些,您应该真正考虑使用它:

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

这行将负责所有 4 个获取路由(索引、创建、编辑、显示)以及所有三个发布/放置/删除路由(存储、更新、删除)。

但对每个人都有自己的。

您应该包含控制器代码。

很可能有一些代码在 Eloquent 模型上尝试 findOrFail(),从而触发此错误。

最新更新