在Lumen获取路线参数

问题描述 投票:3回答:2

当尝试使用$request->route('id')访问Route参数时,在最新版本的Lumen中,我收到错误。

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

它在Laravel中运行良好。

laravel laravel-routing lumen lumen-5.4 lumen-routing
2个回答
4
投票

流明是如此被剥离,路由解析为一个简单的数组,而不是路由对象。

这是一个问题,因为Request::route($key)方法假设Route将有一个parameter方法。

但是如果你调用Request::route(null),将返回完整的Route数组,看起来像这样:

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"
  }
}

其中[2]似乎总是包含Route参数。

我创建了一个简单的帮助器类来处理Lumen上的Route参数。您可以获取,设置和忘记路由参数。如果您需要在中间件中操作它们,这非常有用。

保存在app/Support/RouteParam.phphttps://gist.github.com/westphalen/c3cd187007e0448bcb7fca1de091e4df

并简单地使用它:$id = RouteParam::get($request, 'id');

责怪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.
}

0
投票

要在Lumen中获取请求参数,无论HTTP动词是什么:

$name = $request->input('name');

https://lumen.laravel.com/docs/master/requests#retrieving-input

© www.soinside.com 2019 - 2024. All rights reserved.