skip to Main Content

Is there a possibility to create a routing based on query parameters? For example, an external system is calling the following route:

https://example.com/api?Action=GetOrders&Key=abf24b12c3b2a4e4b4dabbdd

Dependent on the value of Action, I would like to call different controller methods.

How can I do this while maintaining the functionality of the Service Container and Dependency Injection?

I tried like this, but it did not work:

Route::get('api?Action={Action}', function (Request $request, string $action) {
    dd($action);
});

Thanks!

3

Answers


  1. Try this

    Route::get('api', function (Request $request) {
        dd($request->action); });
    
    Login or Signup to reply.
  2. Laravel doesn’t handle query parameters (?) directly in its routes.

    In route

    Route::get('api', 'ApiController@handleAction');
    

    Controller

    public function handleAction(Request $request)
    {
        $action = $request->query('Action');
        // rest of the code
    
    }
    
    Login or Signup to reply.
  3. you should use Controller that can simplify.

    If you want to use laravel routing method use something like

    Route::get('/action/{id}/key/{key}', function (Request $request, string $action, string $key) {
        return 'Action '.$action. 'Key '.$key;
    });
    

    If you like to do with https://example.com/api?Action=GetOrders&Key=abf24b12c3b2a4e4b4dabbdd use $_GET[‘action’] or $request->action; with if in your Controller

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