Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 ModelNotFoundException in Builder.php for Routing

I have a Model Class with name Article.php and use below rout:

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

when input in browser http://localhost:8000/articles/create i see this error : ModelNotFoundException in Builder.php line 125: No query results for model [App\Article].

but when i user below every think is ok:(article insted articles)

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

this is my controller :

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');
    }
}

what happened really ?!!!

like image 879
Bijan Mohammadpoor Avatar asked Dec 10 '22 23:12

Bijan Mohammadpoor


1 Answers

The problem with your code is that in your routes.php your route priority is like this :

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

and when you go to http://localhost:8000/articles/create in your browser laravel catches create as a variable with {id} request in articles/{id} before articles/create gets an opportunity to resolve the route. To solve your problem you must consider the route priority and make the following changes to your route.php file :

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

But if you have a bunch of these in your routes.php file you should really consider using this instead:

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

This single line will take care of all 4 get routes (index, create, edit, show) as well as all three post/put/delete routes of (store, update, delete).

But to each their own.

like image 76
Azeame Avatar answered Jan 31 '23 07:01

Azeame