Andreas
Andreas

Reputation: 687

Laravel reports "Sorry, the page you are looking for could not be found." when I change the order of the routes

I created the two routes and if I use them in the order

Route::get('posts/{post}', 'PostsController@show');
Route::get('posts/create', 'PostsController@create');

Laravel reports "Sorry, the page you are looking for could not be found." But if I change the order to

Route::get('posts/create', 'PostsController@create');
Route::get('posts/{post}', 'PostsController@show');

it works as expected. Why is the first ordering not working?

Upvotes: 2

Views: 953

Answers (3)

Amarnasan
Amarnasan

Reputation: 15529

Because the routing mechanism will only try routes until one of them matches the request, then it stops.

if you have the request "Kill Mark" and you have this list:

Kill all of the mankind
Kill Mark

(all of the mankind dies, Mark included)

but if you have this other list

Kill Mark
Kill all of the mankind

(only Mark dies)

Upvotes: 1

djt
djt

Reputation: 7535

I believe the routes are matched in order

So if you hit this URL: post/create

Route::get("post/{post}", PostsController@show);

Route::get("post/create", PostsController@create);

The first route will be hit, and therefore will try to show a post that doesn't exist (i.e. a post with an ID of "create")

So reordering them does fix this. However, if you used more RESTful routes, it would help avoid this issue:

Route::get("post/{post}", PostsController@show);

Route::post("post", PostsController@create);

Route::patch("post/{post}", PostsController@update);

Etc...

This way, the verb more indicates the way which the route should behave

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Here posts/{post} will handle all requests to /posts/* including /posts/create:

Route::get('posts/{post}', 'PostsController@show');
Route::get('posts/create', 'PostsController@create');

So, you need to define create and similar routes before the posts/{post} route.

Upvotes: 4

Related Questions