Recall & Review
beginner
What is dependency injection in Laravel controllers?
Dependency injection is a way to automatically provide a controller with the objects it needs, like services or repositories, without creating them inside the controller. Laravel does this by passing the needed objects through the controller's constructor or methods.
Click to reveal answer
beginner
How do you inject a service into a Laravel controller constructor?
You add the service type as a parameter in the controller's constructor. Laravel's service container will automatically create and pass the service instance when the controller is used.
Click to reveal answer
intermediate
Why is dependency injection better than creating objects inside controllers?
It makes the code cleaner, easier to test, and more flexible. You can change the service without changing the controller, and Laravel handles creating the objects for you.
Click to reveal answer
beginner
Show a simple example of injecting a repository into a Laravel controller.
class UserController {
protected $userRepo;
public function __construct(UserRepository $userRepo) {
$this->userRepo = $userRepo;
}
public function index() {
return $this->userRepo->allUsers();
}
}Click to reveal answer
intermediate
Can Laravel inject dependencies into controller methods? How?
Yes, Laravel can inject dependencies directly into controller methods by type-hinting the parameters. Laravel will resolve and pass the needed objects automatically when the method is called.
Click to reveal answer
What does Laravel use to automatically provide dependencies to controllers?
✗ Incorrect
Laravel uses a service container to automatically create and inject dependencies into controllers.
Where do you usually declare dependencies for injection in a Laravel controller?
✗ Incorrect
Dependencies are usually declared as parameters in the controller's constructor for injection.
What is a key benefit of using dependency injection in controllers?
✗ Incorrect
Dependency injection makes code easier to test and cleaner by separating concerns.
Can Laravel inject dependencies into controller methods directly?
✗ Incorrect
Laravel supports method injection by type-hinting parameters in controller methods.
What happens if Laravel cannot resolve a dependency in a controller?
✗ Incorrect
If Laravel cannot resolve a dependency, it throws an error indicating the missing binding.
Explain how dependency injection works in Laravel controllers and why it is useful.
Think about how Laravel provides needed objects without manual creation.
You got /4 concepts.
Describe how you would inject a repository into a Laravel controller and use it in a method.
Focus on constructor injection and accessing the injected object.
You got /3 concepts.