Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MrLukman's avatar

Use name in URL instead of id

Hi there i wanna ask how to change my url from myproject/product/{id} to myproject/product/productname.

The productname ofc belongs to the ‘id’ it self, and the product_name is unique. Thanks for the help :)

0 likes
7 replies
rin4ik's avatar
rin4ik
Best Answer
Level 50

you have to override getRouteKeyName method on the Eloquent model

public function getRouteKeyName()
{
    return 'productname';
} 
3 likes
MrLukman's avatar

@rin4ik So in my model i have this

 public function getRouteKeyName()
{
    return 'product_name';
} 

in my routes.php i have this

Route::get('/product/{product}', function(App\Product $product)
{

dd($product);

});

and it works.

But i want to render the page using controller, how do i do that? because this doesn't work

Route::get('/product/{product}',' ProductController@show',function(App\Product $product)
{
return view('guest.productpage')->name('product');

});

Thanks for the help.

Sergiu17's avatar

Hi, Route::get('/product/{product}', 'ProductController@show');

and your show method

public function show(Product $product)
{
    return view('path.to.the.view', compact('product'));
}
2 likes
gwleuverink's avatar

@rin4ik Nice I wasn't aware of that method. I always bind the key for the specific model in the RouteServiceProvider boot method but defining it on the model itself makes more sense :)

@MrLukman When using something other than an id you might want to consider making the product_name column unique so a product name is always assigned to only one record. You can do this by using the unique() method on your migration like so:

$table->string('product_name')->unique();

This method also indexes the column so your queries perform better

1 like
rin4ik's avatar

@MrLukman on your routes specify route like that

 Route::get('/product/{product}', 'ProductController@show'); 

create show method on your ProductController pass to view your data,

public function show(Product $product)
{
    return view('guest.productpage', compact('product'));
}

like this after you can easily render that on the page

3 likes
MrLukman's avatar

Turns out my mistake was

public function show($id)
{
     $product = Product::find($id);

     return view('guest.productpage', compact('product'));
}

this solution works like charm

public function show(Product $product)
{
    return view('guest.productpage', compact('product'));
}

Thanks all for the help :)

5 likes

Please or to participate in this conversation.