Constructor Injection in Laravel: A Clean Way to Inject Dependencies
Laravel 11>
If you're working with services or repositories in your Laravel app (especially with Livewire or Inertia components), you'll likely want to use constructor injection.
Constructor injection is a way to pass dependencies into a class through its constructor, keeping your code clean, testable, and easy to manage.
A Basic Example
use App\Services\WeatherService;
class WeatherController extends Controller
{
protected WeatherService $weather;
public function __construct(WeatherService $weather)
{
$this->weather = $weather;
}
public function show()
{
return $this->weather->getForecast();
}
}
Laravel’s service container automatically resolves the dependency for you—no need to manually instantiate anything.
Why Use Constructor Injection?
- Cleaner code: Keeps business logic out of constructors.
- Easier testing: You can easily mock dependencies in tests.
- Better readability: It’s clear what dependencies a class needs.
- Great with single-responsibility services: Especially common when using the TALL stack to keep Livewire components slim.
Tip for Livewire
When using Livewire, you can’t inject services via the constructor because Livewire serializes components. Instead:
Use the mount()
method
Or grab the service using the container: app(MyService::class)
But in controllers, jobs, listeners, and service classes—constructor injection is gold.
Comments: