【问题标题】:Accessing the current request in controller访问控制器中的当前请求
【发布时间】:2015-11-01 05:26:16
【问题描述】:

在其他MVC框架中,访问当前请求对象就像$this->request一样简单。但是在 Laravel 中,我通常看到 Request $request 通常被注入到每个动作中(public function edit($id, Request $request))。这似乎是一个样板。有没有更好的方法来访问请求? (我现在可以使用继承来使用$this->request,我正在寻找 Laravel 的方式来做到这一点。)

更新:

我发现使用app('request') 可以访问当前请求。但是,我不确定它的潜在利弊。

【问题讨论】:

  • public function edit($id, Request $request) 并不是真正的“样板”,它是依赖注入——这是 Laravel 在大多数地方的做事方式。如果您愿意,也可以使用 Facades:Request::current(),或将请求保存到构造函数中的 $this->request
  • @Ben Request::current() 未定义。 `Request $request` 不在 artisan 创建的方法中。 request 对象几乎总是需要在控制器的方法中,并且作为参数重复发送它绝对是一个样板。

标签: php laravel laravel-5 laravel-request


【解决方案1】:

在 Laravel 5 中,你可以使用 request() 助手:

// to get the current request object
$request = request();

// or to just get a value from the request
$value = request("field", "default");

https://laravel.com/docs/5.6/helpers#method-request

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2023-03-07
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2016-11-14
    相关资源
    最近更新 更多