URL hits wrong LARAVEL controller

In route.php, I defined a route to the controller with two tokens on it.

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

Everything works fine until a URL is called that has the same structure but has nothing to do with the one that should be caught on the route below.

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

So, now I fixed the problem of moving this route to the bottom, but I believe that I need to do something to prevent this behavior in advance, because if I have several routes with different tokens, everything will start every time, and there will be a mess.

So what should he do in these cases?

PS I'm a super newbie with Laravel

+5
source share
3 answers

use some restriction for the route, reference parameters-regular-expression-constraints . For instance:

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

Or you can make it most specific to non-specific. For example, in this sequence:

 Route::get("/admin/tags", '......'); Route::get('/{category}/{slug}', ' projectController@detail '); 
+2
source

If a route needs two tokens, I usually add a prefix so that my routes look like this:

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

or

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

I had the same problem. I have restrictions on each path parameter (as you always need), and, unfortunately, a conflict arises between the following:

 Route::get('{userId}/{path}', [ 'as' => 'products', 'uses' => ' HomeController@click ' ])->where(['id' => '[0-9]+', 'path' => '[0-9a-fA-F]+']); Route::get('link/{link_path}', [ 'as' => 'product-link', 'uses' => ' UserController@productLink ' ])->where(['link_path' => '[0-9a-fA-F]+']); 

If at least one path has an added β€œlink /” in the path, it still tries to hit another. Placing a route with an added β€œlink /” over another route, it takes precedence and works.

Personally, I think that if you have a condition that does not occur on the route, where it should skip the route and go to the next. It makes no sense for me to set a condition that is not actually skipped if the conditions are not met.

Hope this helps someone else with this issue.

0
source

Source: https://habr.com/ru/post/1261364/


All Articles