user11710915
user11710915

Reputation: 434

How to resolve urls correctly in Laravel?

I have url for product details (domain.com/productdetail/1/name-of-product), When i click "about us" page while still in this url, I get an error "this url doesnt exist"(domain.com/productdetail/1/about-us). How can i get the url to resolve correctly to domain.com/about-us

This is my productDetail route

Route::get('/productDetail/{id}/{pro_name}', 
'HomeController@detailPro');

this is about-us route

Route::get('about-us', function(){
return View('about');
});

I would like to get the exactly route (domain.com/about-us) instead of it chaining at the end of the current url (domain.com/productdetail/1/about-us).

Upvotes: 2

Views: 1018

Answers (3)

Nick
Nick

Reputation: 546

Here is an option you can use.

    Route::get('product-detail/{id}/{pro_name}', [
        'as' => 'product.view',
        'uses' => 'HomeController@detailPro',
    ]);

    Route::get('about-us', [
        'as' => 'about'
    ], function(){
          return View('about');
    });

Link:

 <a href="{{route('about')}}">About</a>
 <a href="{{route('product.view',['id' => $id, 'pro_name' => 'name_of_product'])}}">My Product</a>

Upvotes: 0

N69S
N69S

Reputation: 17216

Using alias as @jitheshJose has answered would fix your issue, but i think your issue is as simple as this:

You're on the page "domain.com/productdetail/1/name-of-product" and you have a link with href="about-us".

when this link is clicked, it will lead to "domain.com/productdetail/1/about-us".

to fix this, change the link in the href to href="/about-us".

To understand better what's happening here, lookup the difference between relative link and absolute link.

Upvotes: 0

Jithesh Jose
Jithesh Jose

Reputation: 1814

Better to put routes as named routes.

Route::get('/productDetail/{id}/{pro_name}','HomeController@detailPro')->name('product.view');

Route::get('about-us', function(){
  return View('about');
})->name('about-us');

Call the specific route as

 <a href="{{route('about-us')}}">about us</a>
 <a href="{{route('product.view',['id' => $id, 'pro_name' => 'name_of_product'])}}">View Product</a>

Upvotes: 5

Related Questions