0
0
Laravelframework~5 mins

Dependency injection in controllers in Laravel

Choose your learning style9 modes available
Introduction

Dependency injection helps your controller get the things it needs automatically. This makes your code cleaner and easier to manage.

When your controller needs to use a service or class like a database handler or a mailer.
When you want to write tests easily by replacing real services with fake ones.
When you want to keep your controller code simple and focused on handling requests.
When you want Laravel to create and manage objects for you automatically.
Syntax
Laravel
public function __construct(ServiceClass $service) {
    $this->service = $service;
}
Laravel automatically provides the correct object for the type you ask for.
You just need to type hint the class in the constructor or method parameters.
Examples
This example shows injecting a PaymentService into the controller constructor.
Laravel
use App\Services\PaymentService;

class OrderController extends Controller {
    protected $paymentService;

    public function __construct(PaymentService $paymentService) {
        $this->paymentService = $paymentService;
    }
}
Here, the UserRepository is injected directly into a controller method.
Laravel
use App\Repositories\UserRepository;

class UserController extends Controller {
    public function show(UserRepository $userRepo, $id) {
        return $userRepo->find($id);
    }
}
Sample Program

This controller uses dependency injection to get a NotificationService. When the send method is called, it uses the service to send a message.

Laravel
<?php

namespace App\Http\Controllers;

use App\Services\NotificationService;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    protected NotificationService $notificationService;

    public function __construct(NotificationService $notificationService)
    {
        $this->notificationService = $notificationService;
    }

    public function send(Request $request)
    {
        $message = $request->input('message', 'Hello!');
        return $this->notificationService->sendNotification($message);
    }
}

// NotificationService.php
namespace App\Services;

class NotificationService
{
    public function sendNotification(string $message): string
    {
        // Imagine sending a notification here
        return "Notification sent: " . $message;
    }
}
OutputSuccess
Important Notes

Laravel uses a service container to automatically create and inject dependencies.

You can inject dependencies in the constructor or directly in controller methods.

Make sure the classes you inject are properly imported and registered if needed.

Summary

Dependency injection lets Laravel provide needed objects automatically.

It keeps controllers clean and easy to test.

You just type hint the class in the constructor or method parameters.