Explain Dependency Injection in Laravel.

In Laravel, dependency injection (DI) is a way for classes to receive their dependencies from external sources rather than creating them internally by the class.

🔹 Simple Idea

Instead of doing this ❌:

class UserController {
public function index() {
$service = new UserService(); // tightly coupled
}
}

We do this ✅:

class UserController {
protected $service;

public function __construct(UserService $service) {
$this->service = $service; // injected automatically
}
}

👉 Laravel automatically creates and injects UserService using its Service Container.

🔹 Why Use Dependency Injection?

1. Loose Coupling

Your code doesn’t depend on a specific implementation.

2. Easy Testing

You can replace real classes with mock objects.

3. Cleaner Code

No need to manually create objects everywhere.


🔹 How Laravel Handles DI

Laravel uses a Service Container to resolve dependencies automatically.

Example: Controller Injection

use App\Services\UserService;

class UserController extends Controller
{
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
}


🔹 Method Injection (Very Common in Laravel)

public function store(Request $request, UserService $service)
{
$service->create($request->all());
}

👉 Laravel injects both:

  • Request
  • UserService


🔹 Binding in Service Container

Sometimes you bind interfaces to implementations.

$this->app->bind(
PaymentInterface::class,
RazorpayService::class
);

Now Laravel knows:

When PaymentInterface is needed → use RazorpayService


🔹 Real-World Example

interface PaymentInterface {
public function pay($amount);
}

class RazorpayService implements PaymentInterface {
public function pay($amount) {
return "Paid via Razorpay";
}
}

class OrderController {
public function checkout(PaymentInterface $payment) {
return $payment->pay(1000);
}
}

👉 Laravel injects RazorpayService automatically.


🔹 Types of Dependency Injection in Laravel

  1. Constructor Injection (most common)
  2. Method Injection
  3. Interface Injection (via binding)

To Top