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.
CodePudding user response:
- 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
CodePudding user response:
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
