Laravel multiple optional parameter not working
Using the following route with two optional parameters,
Route::get('/abc-{abc_id?}/xyz-{xyz_id?}', function($abc_id=0, $xyz_id=0)
{
return "\n hello ... World";
});
For inquiries
/abc-1/xyz-15 - Hello World /abc-1/xyz - Hello World
But for
/abc-/xyz-15 - 404 /abc/xyz-15 - 404
Why is the first optional parameter not working correctly? Are there any alternative solutions?
Note that both parameters are specified in url not as get attribute
source to share
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 a part of /xyz-
your route is required and it comes after the first optional parameter, that first optional parameter becomes necessary.
One option you have is to include the id prefix as part of the parameter and use pattern matching to enforce the route format. Then you need to parse the actual id 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 "\n hello ... World";
})->where([
'abc_id' => 'abc(-[^/]*)?',
'xyz_id' => 'xyz(-[^/]*)?'
]);
source to share