TortelliEngineer TortelliEngineer - 3 months ago 13
PHP Question

Laravel Request: it's correct injecting Request directly in the controller constructor?

In a Laravel Controller, if all the functions use Request, it's correct to inject the Request directly in the constructor instead of the function?

The code below works, I was just wondering if it's correct and if it has side effects...

class BananaController extends Controller
{

protected $request; // request as an attribute of the controllers

public function __construct(Request $request)
{
$this->middleware('auth');
$this->request = $request; // Request becomes available for all the controller functions that call $this->request
}

public function store()
{
$this->validate($this->request, [
'text' => 'required',
]);

// I save the banana attributes and the controller continues...


Go easy on me, first question on stackoverflow ever :-)

[ADDENDUM] To be clear, the "conventional" code would be:

class BananaController extends Controller
{

public function __construct()
{
$this->middleware('auth');
}

public function store(Request $request)
{
$this->validate($request, [
'text' => 'required',
]);

// I save the banana attributes and the controller continues...

Answer

If all the methodos in your cotroller BananaController are using the Request class, the most common way to inject dependencies is via a class's constructor as well as shown in the example of your question.

There are several advantages to using constructor injection:

  • If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.

  • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.

Note that these advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.