Dependency injection is a method used to detach hard-coded class dependencies. The dependencies are inserted at run-time, which allows for greater pliability as dependency execution may be easily reciprocated.
In Laravel, dependency injection is the process of injecting class dependencies into a class through a constructor or setter method. This allows your code to look clean and run faster.
Dependency injection involves the use of a Laravel service container, a container that is used to manage class dependencies.
We type-hint
any dependencies needed by the routes into the callback function like this:
<?php
class Property
{
//
}
Route::get('/', function (Property $property) {
die(get_class($property));
});
In the example above, hitting your application’s /
route will automatically determine the Property
class and inject it into your route’s handler.
So, when we do die(get_class($property))
, we would see an empty class, which implies that we could easily use the property
class.
Dependency injection via routes is one of the ways dependency injection is done. This method is used to inject dependency directly from the route just before it gets to the controller.