Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use dependency injection for Request object vs request() helper in Laravel?

Is there any benefit to injecting the Request object into your controller method like this:

use Request;

class WidgetController
{
  public function create(Request $request)
  {
    $name = $request->input('name');
  }
}

Versus eliminating the use statement and object injection and simply using the helper:

class WidgetController
{
  public function create()
  {
    $name = request('name');
  }
}
like image 601
wheelmaker Avatar asked Sep 23 '18 22:09

wheelmaker


3 Answers

The request helper is just a shortcut to Request::input('name'). The code for the request helper is defined like this request helper

app('request')->input($key, $default);

The app is the Container that manages the Dependency injection of Laravel. It will resolve the dependency that correspond to the name request which is an instance of Illuminate\Http\Request and call on it the method input passing the name of the key you want to retrieve.

There is really no difference, one is a shortcut of the other.

like image 165
Yves Kipondo Avatar answered Nov 15 '22 04:11

Yves Kipondo


The primary reason to use injection is because of testing. If you use request() then you need to initialize the Laravel app since request() calls app('request'). If app('request') is not initialized then your tests will generate an error.

When you use injection you pass on the Request object to the method. This means that during testing you can create your own "dummy" request and pass that on to the method without having to initialize app(). Then you can test the method and only the method without and dependencies to anything else.

like image 25
Martijn Hiemstra Avatar answered Nov 15 '22 05:11

Martijn Hiemstra


First of all, code-styling and readability. The first one is way more readable. Second thing from top of my mind is that, if you use request() helper, you can not validate the request.

Let's say your request must contain a parameter title and body. If the parameter is not there, it should never reach that endpoint. Using the helper(), there is not way to do it. While, using the first method, there is really convenient way of doing that.

class StoreRequest extends FormRequest
{
    public function rules()
    {
        return [
            'title' => 'required',
            'body' => 'sometimes'
        ];
    }
}

And than just:

use StoreRequest;

class WidgetController
{
  public function create(StoreRequest $request)
  {
    $name = $request->input('name');
  }
}
like image 24
boka18 Avatar answered Nov 15 '22 04:11

boka18