php - Laravel any route with optional GET parameter
I am using Laravel 8.1. Currently I have this catch-all route:
Route::any('/{any}', [IndexController::class, 'index'])->where('any', '.*');
This works great for all URLs. However if I want to attach a GET parameter for ID, I have do this:
/api/products/view?id=1
Instead of that I want to do this:
/api/products/view/1
My function signature is like this:
public function index(Request $request) {}
I only want ID as an optional GET parameter.
Answer
Solution:
You can add another optional route parameter and specify a pattern in the where for the any
parameter - ".*" will not work with optional parameter after any
Route::any('/{any}/{id?}', [IndexController::class, 'index'])->where('any', '[A-Za-z-_]+');
public function index(Request $request)
{
$id = $request->route('id');
}
Answer
Solution:
You can add another route param and get it in the Controller like I have below:
Route:
Route::any('/{any}/{id}', [IndexController::class, 'index'])->where('any', '.*');
Controller:
public function index($any, $id)
{
// $id will be passed in.
}
Source