mbrown1408's avatar

Order of Routes

I'm following a tutorial, and I've found that the order of the routes in the web.php file seem to matter.

I have the following in the web.php and it works as expected:

Route::get('/home', 'HomeController@index')->name('home'); Route::get('/blog', 'PostController@index'); Route::get('/blog/create', 'PostController@create'); Route::get('/blog/{post}', 'PostController@show'); Route::post('/blog', 'PostController@store');

however, if I have the postcontroller@show method before the postcontroller@create, the create page is blank. Can somebody explain to me why this matters and how to know the proper order if I had a lot of routes? I don't get the expected pattern and this wasn't talked about in the tutorial. I'm using Laravel 5.7.

Thank you!

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

If you have the create route after the show route, then the route wildcard will see 'create' as a parameter because you are matching the pattern blog/{id} - Laravel has no way to know that the id part should be a number unless you provide a regular expression pattern for that wildcard:

Route::get('/blog/{post}', 'PostController@show')->where('id', '[0-9]+');

Now the show route will only be matched when a number is in the second URI segment, and create will not be mismatched

mbrown1408's avatar

Thank you @tykus for the explanation. That makes sense to me. Much appreciated.

Please or to participate in this conversation.