Home > OS >  Laravel returning the same view for 2 different routes
Laravel returning the same view for 2 different routes

Time:12-11

Laravel is somehow getting the same view for 2 different routes and I can't figure out why since I'm not very familiar with Laravel.

Here's the 2 routes in question :


Route::get('/{label}', [BookController::class, 'listbyCat'])->name('bycats');

Route::get('/{id}', [BookController::class, 'singlebook'])->name('book');

The first route is the one returning the view (calling the method), that means if I switch between them it wall call singlebook() in both routes.

HTML :

 <a href="{{ route('book', $book->id) }}">Book</a>

 <a href="{{ route('bycats', $cat->id) }}">Category</a>

CodePudding user response:

Should be obvious that when there is no other way for laravel to determine which route you want, that it will route to the first one it has in its routing table.

This would be a simple workaround that should illustrate what you are missing.

Route::get('/cat/{label}', [BookController::class, 'listbyCat'])-name('bycats');
Route::get('/book/{id}', [BookController::class, 'singlebook'])->name('book');

Artisan should be your goto tool whenever you first encounter a problem like this.

php artisan route:list

CodePudding user response:

When you try to access any resource you gonna write the route on the browser so what if i just had two resources like those:

Route::get('/book/{label}', [BookController::class, 'listbyCat'])->name('bycats');

Route::get('/book/{id}', [BookController::class, 'singlebook'])->name('book');

And i am trying to access localhost::8080/book/5

So what tells laravel from this route that this route belongs to which one of the resources ?

Nothing !! Cause 5 could be considered as a label or id

So you should change the route to be identifiable to laravel

Try to change one of the routes, Example:

Route::get('/book/by/{label}', [BookController::class, 'listbyCat'])->name('bycats');

Route::get('/book/{id}', [BookController::class, 'singlebook'])->name('book');
  • Related