Yes this is possible but if you want to follow the recommended conventions you should use / instead of &
Jan 24, 2024
30
Level 1
Laravel optional multiple params routes
Hi, I just wondered if is possible to make a route like this Route::get('/products/{id?}&{brand?}') ??
For example: I need to be in URL localhost/products/1&nike
Level 80
@abdullaf You have an ID in the URI. That suggests you have an “index” route and a “show” route. I don’t really see what tracking has to do with anything.
Route::get('/products', [ProductController::class, 'index']);
Route::get('/products/{id}', [ProductController::class, 'show']);
You can then use a query string on your index view to filter results, i.e. /products?brand=nike to only show Nike-branded products in the listing:
public function index(Request $request)
{
$products = Product::query()
->when($request->query('brand'), function (Builder $query, string $brand) {
$query->where('brand', '=', $brand);
})
->paginate();
return view('products.index', compact('products'));
}
public function show(Product $product)
{
return view('products.show', compact('product'));
}
There’s no need to try and shoehorn multiple responsibilities into a single controller action.
Please or to participate in this conversation.