Which of the following is the correct way to inject a service into a Laravel controller constructor?
easy📝 Syntax Q12 of 15
Laravel - Controllers
Which of the following is the correct way to inject a service into a Laravel controller constructor?
Apublic function __construct($service) { $this->service = new Service(); }
Bpublic function __construct(Service $service) { $this->service = $service; }
Cpublic function __construct() { $this->service = Service::class; }
Dpublic function __construct(Service $service) { $service = new Service(); }
Step-by-Step Solution
Solution:
Step 1: Check constructor parameter type hinting
public function __construct(Service $service) { $this->service = $service; } correctly type hints the Service class in the constructor parameter.
Step 2: Verify assignment to class property
public function __construct(Service $service) { $this->service = $service; } assigns the injected service to a class property for later use, which is correct.
Final Answer:
public function __construct(Service $service) { $this->service = $service; } -> Option B
Quick Check:
Constructor injection = type hint + assign property [OK]
Quick Trick:Type hint service in constructor and assign to property [OK]
Common Mistakes:
Not type hinting the service class in constructor
Creating new service instance inside constructor instead of injecting
Assigning class name string instead of object
Master "Controllers" in Laravel
9 interactive learning modes - each teaches the same concept differently