laravel

Guide To Injecting Dependencies Into Controllers


Laravel’s facades present a simple interface to the most useful classes in Laravel’s codebase. You can get information about the current request and user input, the session, caches, and much more.

But if you prefer to inject your dependencies, or if you want to use a service that doesn’t have a facade, you’ll need to find some way to bring instances of these classes into your controller.

All controller methods (including the constructors) are resolved out of Laravel’s container, which means anything you typehint that the container knows how to resolve will be automatically injected.

As a nice example, what if you’d prefer having an instance of the Request object instead of using the facade? Just typehint Iluminate\Http\Request in your method parameters:]

public function store(\Illuminate\Http\Request $request)
{
    $organization = new Organization;
    $organization->name = $request->input('name');
    $organization->years = $request->input('years');
    $organization->save();
   
    return redirect('organizations');
}

So, you have defined a parameter that must be passed into the store() method. And since you typehinted it, and since Laravel knows how to resolve that class name, you are going to have the Request object ready for you to use in your method with no work on your part. No explicit binding, no anything else – it’s just there as the $request variable.

Btw, this is actually how I and many other Laravel developers prefer to get the user input: inject an instance of the Request and read the user input from there, instead of relying on the Input facade.

About the author

Avatar

laravelrecipies