Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL hit the wrong controller LARAVEL

In route.php I defined a route to a controller with 2 tokens on it.

Route::get('/{category}/{slug}', 'projectController@detail');

Everything is working fine till when there is a call to a URL that have the same structure but has nothing to do with the one that has to be caught by that route shown below.

So when I have for example "/admin/tags", the controller below is triggered because it has the same structure of "/{category}/{slug}" and of course it gives me an error, because it doesn't find a variable.

So now I fixed the problem moving that route on the bottom, but I believe I have to do something to prevent this behavior in advance, cause if I have multiple routes with different tokens everything would be triggered every time and there would be a mess.

So, what is it supposed to do in these cases?

P.S. I'm super beginner with Laravel

like image 451
rolfo85 Avatar asked Oct 17 '22 20:10

rolfo85


2 Answers

use some constraint to the route, reference parameters-regular-expression-constraints. For example:

Route::get('user/{name}', function ($name) {
    //
})
->where('name', '[A-Za-z]+');

Or you can make the most specific before unspecific one. For example, in this sequence:

Route::get("/admin/tags", '......');
Route::get('/{category}/{slug}', 'projectController@detail');
like image 84
LF00 Avatar answered Oct 29 '22 15:10

LF00


if route need two token like that, i'm usually add prefix so my routes looks like this

Route::get('/categories/{category}/slug/{slug}', 'ProjectController@detail');

or

Route::get('/categories/{category}/{slug}', 'ProjectController@detail');
like image 30
imansyaefulloh Avatar answered Oct 29 '22 16:10

imansyaefulloh