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 :)
you have to override getRouteKeyName method on the Eloquent model
public function getRouteKeyName()
{
return 'productname';
}
@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.
Hi,
Route::get('/product/{product}', 'ProductController@show');
and your show method
public function show(Product $product)
{
return view('path.to.the.view', compact('product'));
}
@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
@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
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 :)
Please sign in or create an account to participate in this conversation.