9

In other MVC frameworks, accessing to the current request object is as simple as $this->request. However in the Laravel, I generally see that Request $request is generally injected to each action (public function edit($id, Request $request)). It seems like a boilerplate. Is there any better way to access the request? (I now that I can use inheritance to use $this->request, I am looking for the Laravel way to do that.)

update:

I found out using app('request') I can access to the current request. However, I am not sure of its potential pros and cons.

miken32
  • 42,008
  • 16
  • 111
  • 154
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • 6
    `public function edit($id, Request $request)` isn't really "boilerplate", it's dependency injection -- that's Laravel's way of doing things most places. You can also use Facades if you prefer: `Request::current()`, or save the request to `$this->request` in your constructor. – Ben Claar Aug 09 '15 at 02:28
  • @Ben `Request::current()` is undefined. ` Request $request` is not in the methods created by artisan. `request` object is almost always need in controller's method and sending it repetitively as a parameter is definitely a boilerplate. – Handsome Nerd Aug 09 '15 at 05:13

1 Answers1

9

In Laravel 5, you can use the request() helper:

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

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

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

miken32
  • 42,008
  • 16
  • 111
  • 154