Dependency Injection (DI) is one of the most powerful features in Laravel. It helps developers write clean, maintainable, and testable code by reducing tight coupling between classes.
If you've ever wondered why Laravel automatically creates objects without using the new keyword, the answer is Dependency Injection powered by Laravel's Service Container.
In this guide, you'll learn everything about Dependency Injection in Laravel 13 with real-world examples.
What is Dependency Injection?
Dependency Injection is a design pattern where an object receives its dependencies from an external source rather than creating them itself.
Without Dependency Injection
class UserController
{
protected $userService;
public function __construct()
{
$this->userService = new UserService();
}
}
Problems
- Tight coupling
- Difficult to test
- Hard to replace implementation
- Violates SOLID principles
With Dependency Injection
class UserController
{
public function __construct(
protected UserService $userService
) {}
}
Laravel automatically creates the UserService object. No new keyword required.
Why Use Dependency Injection?
Benefits include:
- Cleaner code
- Better architecture
- Easier testing
- Loose coupling
- Easy maintenance
- Reusable services
- Supports SOLID principles
How Laravel Dependency Injection Works
Laravel has a powerful Service Container. Whenever Laravel sees this:
public function __construct(UserService $service)
It automatically does something similar to:
$service = new UserService();
return new UserController($service);
Everything happens automatically.
Example Project Structure
app/
│
├── Http/
│ └── Controllers/
│
├── Services/
│ └── UserService.php
│
└── Repositories/
└── UserRepository.php