Laravel: Controller Dependency Injection

By | February 18, 2018

The Laravel service container is used to resolve all Laravel controllers. Hence, you are able to type-hint any dependencies that your controller may need in its constructor.

Laravel automatically look for type hinted dependencies of controller constructor or controller method and if it knows how to create instance of dependencies it will do that and provide the same.

Lets create a custom service class named app/Services/Demo.php and inject it as dependency for a constructor of a controller named app\Http\Controllers\UserController.php

Now, each method of UserController will have access to a Demo object and can be used as per need.

Similarly, you may also type-hint dependencies on your controller’s methods.

If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies:

Thanks :)

Leave a Reply

Your email address will not be published. Required fields are marked *