🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Dependency Injection

Dependency injection hands a class the objects it needs. Laravel builds those objects and passes them in.

Ask for the service

The constructor asks for the service, and the word private stores it on the controller.

public function __construct(private BookService $books) {}

Use the service

The controller receives the service instead of creating it.

public function index()
{
    return 'Featured book: ' . $this->books->title();
}

The service class

The service holds one method that returns a book title.

public function title(): string
{
    return 'Dune';
}

Example

use App\Services\BookService;

Route::get('/featured', [ShelfController::class, 'index']);

class ShelfController extends Controller
{
    public function __construct(private BookService $books)
    {
    }

    public function index()
    {
        return 'Featured book: ' . $this->books->title();
    }
}

class BookService
{
    public function title(): string
    {
        return 'Dune';
    }
}

Key points

  • Dependency injection: passing the objects a class needs into that class, instead of the class creating them.
  • Service: a small class that holds one piece of logic, such as finding a book title.
  • Use a constructor to ask for a service, and Laravel supplies it.
  • Use the injected service inside the action through $this->books.

In this example, the controller file imports BookService at the top. The route sends GET requests for /featured to the index action of ShelfController. The controller asks for a BookService in its constructor, and Laravel passes one in. The index action asks the service for its title. The service returns Dune, so the page shows Featured book: Dune.

Note

A class that takes its needs as constructor arguments is easy to test.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does dependency injection do?