Reputation: 944
Case 1: web.php
:
Route::get('foo/{id}', function () {
return 'Route 1';
});
Route::get('foo/bar', function () {
return 'Route 2';
});
Route::get('foo/bar', function () {
return 'Route 3';
});
When I browse to localhost/foo/bar
I got Route 1
which correct since the url match the first route.
Case 2: web.php
:
Route::post('foo/{id}', function () {
return 'Route 1';
});
Route::get('foo/bar', function () {
return 'Route 2';
});
Route::get('foo/bar', function () {
return 'Route 3';
});
When I browse to localhost/foo/bar
I got Route 3
.
My question is why i got Route 3
intead of Route 2
. Isn't logical to get Route 2
since the url match the second route first?! Why does Laravel continue to match the routes after match is found (route 2 in my case)?
Upvotes: 2
Views: 2286
Reputation: 13447
The second foo/bar
route overrides the first, because the HTTP Method and URI are the same.
The HTTP Method + URI combo acts as a primary key for a route. The combination of the two have to be unique - you can't have two different destinations for the same route.
So, Laravel takes a "last in, first out" approach, where any previous definition (e.g. "Route 2") is overwritten. You can confirm this by running php artisan route:list
in the command line to see what route definitions Laravel will actually attempt to match.
Upvotes: 3
Reputation: 11
In case 1, Route 1 has priority because it has generated route (foo/{id}
)
In case 2, Route 1 has priority when you use post method otherwise last route has priority which is route 3.
Upvotes: 1