Search code examples
laravellaravel-routinglumenlumen-5.4lumen-routing

Getting route parameters in Lumen


When trying to access Route parameters, using $request->route('id'), in latest version of Lumen, I get an error.

lumen.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: 
Call to a member function parameter() on array

It works fine in Laravel.


Solution

  • Lumen is so stripped down, that the Route resolves to a simple array, rather than a Route object.

    This is a problem, since the Request::route($key) method assumes the Route will have a parameter method.

    But if you call Request::route(null), the complete Route array will be returned, looking something like this:

    array(3) {
      [0]=>
      int(1)
      [1]=>
      array(2) {
        ["uses"]=>
        string(40) "App\Http\Controllers\SomeController@index"
        ["middleware"]=>
        array(2) {
          [0]=>
          string(4) "auth"
          [1]=>
          string(4) "example"
        }
      }
      [2]=>
      array(1) {
        ["id"]=>
        string(36) "32bd15fe-fec8-11e7-ac6b-e0accb7a6476"
      }
    }
    

    Where [2] always seems to contain the Route parameters.

    I made a simple helper class to work with the Route parameters on Lumen. You can get, set and forget route parameters. This is works great if you need to manipulate them in your middleware.

    Save in app/Support/RouteParam.php: https://gist.github.com/westphalen/c3cd187007e0448bcb7fca1de091e4df

    And simply use it like this: $id = RouteParam::get($request, 'id');

    Blame illuminate/http/Request.php:

    /**
     * Get the route handling the request.
     *
     * @param  string|null  $param
     *
     * @return \Illuminate\Routing\Route|object|string
     */
    public function route($param = null)
    {
        $route = call_user_func($this->getRouteResolver());
    
        if (is_null($route) || is_null($param)) {
            return $route;
        }
    
        return $route->parameter($param); // can't call parameter on array.
    }