skip to Main Content

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


  1. 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:

    Route::get('/{category_id?}/system/batches/{batch_id}', 'CirculyDbSettingsBatchSettingController@show');
    
    // Controller method with an optional parameter
    public function show($batch_id, $category_id = null): JsonResponse
    {
        // Your controller logic here
    }
    

    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 of null, which allows it to match the argument name and automatically set it to null if category_id is not present in the URI. This way, you can achieve the desired behavior in Laravel, similar to what you experienced in Lumen.

    Login or Signup to reply.
  2. 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:

    Route::get('{category_id}/system/batches/{batch_id}', 'CirculyDbSettingsBatchSettingController@show');
    
    // controller method, category_id can be ignored  
    public function show(): JsonResponse {
        request()->route('batch_id');
    }
    

    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 own ControllerDispatcher 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search