0

I have route in web.php

Route::get('{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories');

{cat} is slug of the particular category whose products are to be shown.

I have issue with another route here

Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])->name('show_blogs_toWebsite');

When i hit this route it goes to first one. How can i differentiate these two. Please help me. thanks.

2 Answers2

1
  1. You can change first route url by adding a string before or after {cat} like Route::get('/category/{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories')

Also , if you will change the ordering of routes , It will be work fine

Note: run php artisan route:clear command before testing

ch_abid
  • 36
  • 3
  • yes i understand your point and i tried it and it works fine. But i am wondering that why first route called when i am not sending {cat} parameter in any other route – muhammad adnan Jan 31 '22 at 06:44
  • @muhammadadnan `{cat}` is a variable and can have any value (including `blogs`) so it basically conflicts with the `blogs` route – apokryfos Jan 31 '22 at 06:51
  • @muhammadadnan Basically you are not sending a parameter, you are building a route URL. When opening the route Laravel will take the first route that matches the URL. – Gert B. Jan 31 '22 at 07:30
0

Normally The one that has priority should be declared first e.g.

Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])->name('show_blogs_toWebsite');
Route::get('{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories');

You have some other options as well like e.g. handle this in the route handler:

Route::get('{cat}',function ($cat) {
    if ($cat === 'blogs') return app()->call([WebsiteController::class,'show_blogs_toWebsite']); 
    return app()->call([WebsiteController::class,'dbCategories']);
});

the downside of this is that you lose the route name.

Another alternative is to specify a regex to match {cat} e.g.

Route::get('{cat}',[WebsiteController::class,'dbCategories'])
    ->name('dbCategories')
    ->where('cat', '^((?!blogs).)*$');
Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])
    ->name('show_blogs_toWebsite');

The regex above comes from https://stackoverflow.com/a/406408/487813

apokryfos
  • 38,771
  • 9
  • 70
  • 114