Laravel Dependency Injection Guide

Dependency injection in Laravel is implemented through the service container. When you need to use an instance of a class, you can declare the required dependency class directly in the constructor, and Laravel will automatically resolve the instance you need.

For example, suppose there is a UserService class that needs to depend on a UserRepository class, dependency injection can be implemented like this:

namespace App\Services;

use App\Repositories\UserRepository;

class UserService
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getAllUsers()
    {
        return $this->userRepository->getAll();
    }
}

Then, when using the UserService class in the controller, Laravel will automatically inject an instance of UserRepository.

namespace App\Http\Controllers;

use App\Services\UserService;

class UserController extends Controller
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function index()
    {
        $users = $this->userService->getAllUsers();
        return view('users.index', ['users' => $users]);
    }
}

By doing this, dependency injection can be achieved, making the code more flexible and easier to maintain.

bannerAds