Laravel 5.6从资源中获取中间件中的请求ID

时间:2018-12-06 13:03:25

标签: php laravel

我的资源路线:

Route::resource('imagerequests', 'ImageRequestController');

在浏览器中看起来像这样:

/imagerequests/19/edit

在控制器构造器中执行此操作是因为仅当用户转到编辑页面时才需要中间件:

$this->middleware('edit')->only('edit');

我的editMiddleware:

public function handle($request, Closure $next)
{
    dd($request->id);
}

这将返回null

我也尝试过此操作,并且还会返回null

public function handle($request, Closure $next)
{
    dd($request->imagerequests);
}

访问

时如何访问ID

编辑

dd($request);

的结果
Request {#42 ▼
  #json: null
  #convertedFiles: null
  #userResolver: Closure {#295 ▶}
  #routeResolver: Closure {#302 ▶}
  +attributes: ParameterBag {#44 ▼
    #parameters: []
  }
  +request: ParameterBag {#50 ▼
    #parameters: []
  }
  +query: ParameterBag {#50 ▶}
  +server: ServerBag {#46 ▶}
  +files: FileBag {#47 ▶}
  +cookies: ParameterBag {#45 ▶}
  +headers: HeaderBag {#48 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/imagerequests/19/edit"
  #requestUri: "/imagerequests/19/edit"
  #baseUrl: ""
  #basePath: null
  #method: "GET"
  #format: null
  #session: Store {#356 ▶}
  #locale: null
  #defaultLocale: "en"
  -isHostValid: true
  -isForwardedValid: true
  basePath: ""
  format: "html"
}

编辑2

dd($next);

的结果
Closure {#294 ▼
  class: "Illuminate\Routing\Pipeline"
  this: Pipeline {#310 …}
  parameters: {▶}
  use: {▶}
  file: "C:\Users\EXM235\Desktop\acl-poc\vendor\laravel\framework\src\Illuminate\Routing\Pipeline.php"
  line: "28 to 36"
}

1 个答案:

答案 0 :(得分:0)

我不能百分百确定它对中间件的工作方式是否与对Controllers相同,但是在Controller中,您需要键入来自URL的模型,像这样:

public function handle($request, Imagerequest $imagerequest, Closure $next)
{
    $imagerequest->id
}

当然,您还需要在开头添加:

use App\Imagerequest;