I started learning laravel and couldn’t figure out how to solve a problem. For example if i want to create a route for products i can use a route like below.
JavaScript
x
Route::get('/product/{slug}',[ProductController::class,'index']);
In this approach we would get something like this localhost/product/macbook-pro. However i want to create a url like localhost/macbook-pro. In my project, where I did this with plain PHP using the $route variable, I was creating a table called links in the database and saving the links in it. I was doing the table structure and PHP side control as follows. url | type | type_id — | — | — macbook-pro | product | 1 msi-laptop | product | 2
JavaScript
if ($query = DB::table('links')
->where('url', route(0))
->first()
) {
$type_id = $query['type_id'];
$route[0] = $query['type'];
}
How can i get the same approach in laravel ?
Advertisement
Answer
You can customise key with Implicit Binding
JavaScript
Route::get('/{product:slug}',[ProductController::class,'index']);
With this, you need unique field slug
in your product model.