I’ve been working with Lumen, and I’ve noticed a convenient feature where I can ignore some route parameters, and the parameter will automatically match the name of the argument. However, in Laravel, it seems like this option is not available by default.
eg:
Route::get('{category_id}/system/batches/{batch_id}', 'CirculyDbSettingsBatchSettingController@show');
// controlloer method, category_id can be ignored
public function show($batch_id): JsonResponse
Is there a way to achieve similar behavior in Laravel, where I can ignore specific route parameters and have them automatically match the corresponding argument name?
2
Answers
In Laravel, you can achieve a behavior similar to Lumen by using optional parameters in your routes. The official documentation provides guidance on how to do this. Let’s say you want to make the
category_id
parameter optional and have it automatically match the argument name. Here’s how you can achieve that:In this example, we’ve made
category_id
an optional parameter by adding a?
after its name in the route definition. The controller method includes the optional parameter$category_id
with a default value ofnull
, which allows it to match the argument name and automatically set it to null ifcategory_id
is not present in the URI. This way, you can achieve the desired behavior in Laravel, similar to what you experienced in Lumen.This does not seem to be possible because the routing code is completely different.
You can achieve something similar to what you need by using the route method on the request:
As an aside Lumen uses
Container::call
to call controller methods which will do dependency injection but also match named parameters, while laravel does a simple method invocation, so presumably if you implement your ownControllerDispatcher
you can possibly emulate this behaviour. Original source for that is here. I briefly tried but it’s a bit too complex to do with reasonable effort.