0
0
Laravelframework~30 mins

Dependency injection in controllers in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Dependency Injection in Laravel Controllers
📖 Scenario: You are building a simple Laravel web application that manages books. You want to use dependency injection in a controller to get a service that handles book data.
🎯 Goal: Create a Laravel controller that uses dependency injection to receive a BookService instance. This service will provide a method to get all books. You will set up the service, inject it into the controller, and call its method.
📋 What You'll Learn
Create a BookService class with a method getAllBooks() that returns an array of book titles.
Create a controller named BookController.
Inject the BookService into the BookController constructor using dependency injection.
Use the injected BookService inside a method index() in the controller to get all books.
💡 Why This Matters
🌍 Real World
Dependency injection is a common pattern in Laravel to manage class dependencies cleanly. It helps you write modular and testable code.
💼 Career
Understanding dependency injection in controllers is essential for Laravel developers. It is widely used in professional Laravel projects to manage services and repositories.
Progress0 / 4 steps
1
Create the BookService class
Create a class called BookService with a public method getAllBooks() that returns an array with these exact book titles: 'The Hobbit', '1984', and 'Pride and Prejudice'.
Laravel
Need a hint?

Define a class named BookService inside the App\Services namespace. Add a public method getAllBooks() that returns the array of book titles.

2
Create the BookController with constructor injection
Create a controller class called BookController inside the App\Http\Controllers namespace. Add a constructor that accepts a BookService parameter and stores it in a private property called bookService.
Laravel
Need a hint?

Remember to import BookService with a use statement. Define a private property bookService and assign the injected service to it in the constructor.

3
Add the index method to use the injected service
Inside the BookController class, add a public method called index(). Inside this method, call $this->bookService->getAllBooks() and store the result in a variable called books.
Laravel
Need a hint?

Define the index() method to call the service method and return the list of books.

4
Complete the controller with namespace and use statements
Ensure the BookController class has the correct namespace App\Http\Controllers and includes the use App\Services\BookService; statement at the top. Confirm the full controller code includes the constructor and index() method using dependency injection.
Laravel
Need a hint?

Make sure the controller file starts with the correct namespace and imports the BookService. The class should have the constructor and index() method as before.