While using following route with 2 optional parameters,
Route::get('/abc-{abc_id?}/xyz-{xyz_id?}', function($abc_id=0, $xyz_id=0)
{
return "
hello ... World";
});
For requests
/abc-1/xyz-15 - Hello World
/abc-1/xyz - Hello World
But for
/abc-/xyz-15 - 404
/abc/xyz-15 - 404
Why first optional parameter not working properly? Is there any alternate solutions?
Please note both parameters are in url not as a get attribute
Everything after the first optional parameter must be optional. If part of the route after an optional parameter is required, then the parameter becomes required.
In your case, since the /xyz-
portion of your route is required, and it comes after the first optional parameter, that first optional parameter becomes required.
One option you have would be to include the id prefix as part of the parameter and use pattern matching to enforce the route format. You would then need to parse the actual id out from the parameter values.
Route::get('/{abc_id?}/{xyz_id?}', function($abc_id = 0, $xyz_id = 0) {
$abc_id = substr($abc_id, 4) ?: 0;
$xyz_id = substr($xyz_id, 4) ?: 0;
return "
hello ... World";
})->where([
'abc_id' => 'abc(-[^/]*)?',
'xyz_id' => 'xyz(-[^/]*)?'
]);