Bird
Raised Fist0
Laravelframework~20 mins

Dependency injection in controllers in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Laravel Dependency Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when injecting a service in a Laravel controller?
Consider a Laravel controller that injects a service class via its constructor. What will be the output when calling the controller method that uses this service to return a greeting message?
Laravel
<?php
namespace App\Http\Controllers;
use App\Services\GreetingService;

class WelcomeController extends Controller
{
    protected $greetingService;

    public function __construct(GreetingService $greetingService)
    {
        $this->greetingService = $greetingService;
    }

    public function greet()
    {
        return $this->greetingService->sayHello();
    }
}

// GreetingService.php
namespace App\Services;

class GreetingService
{
    public function sayHello()
    {
        return 'Hello, Laravel!';
    }
}
A"Hello, Laravel!"
BAn error: Class 'GreetingService' not found
C"Hello from controller!"
DNull or empty response
Attempts:
2 left
💡 Hint
Think about how Laravel automatically resolves classes injected in the constructor.
❓ state_output
intermediate
2:00remaining
What is the value of the injected repository property after controller instantiation?
Given a Laravel controller that injects a UserRepository interface, what will be the value of the repository property after the controller is created?
Laravel
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepositoryInterface;

class UserController extends Controller
{
    private UserRepositoryInterface $repository;

    public function __construct(UserRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }

    public function index()
    {
        return $this->repository->allUsers();
    }
}
AAn empty array
BAn instance of a class implementing UserRepositoryInterface
CAn error: Cannot instantiate interface UserRepositoryInterface
DNull because interfaces cannot be instantiated
Attempts:
2 left
💡 Hint
Laravel binds interfaces to concrete classes in the service container.
📝 Syntax
advanced
2:00remaining
Which option correctly injects a service into a Laravel controller method?
You want to inject a Logger service directly into a controller method instead of the constructor. Which code snippet correctly achieves this?
Laravel
<?php
namespace App\Http\Controllers;
use App\Services\Logger;

class LogController extends Controller
{
    public function logAction( /* what goes here? */ )
    {
        // Use $logger to log a message
        $logger->info('Action logged');
        return 'Logged';
    }
}
ALogger $logger
Bpublic Logger $logger
CLogger $logger = new Logger()
DLogger $logger = null
Attempts:
2 left
💡 Hint
Method injection requires type hinting the parameter without visibility or default values.
🔧 Debug
advanced
2:00remaining
Why does this Laravel controller injection cause an error?
Examine the following controller code. Why does Laravel throw a binding resolution exception when trying to instantiate this controller?
Laravel
<?php
namespace App\Http\Controllers;
use App\Services\PaymentGateway;

class PaymentController extends Controller
{
    public function __construct(PaymentGateway $gateway)
    {
        $this->gateway = $gateway;
    }
}
AThe constructor is missing a return type
BThe property $gateway is not declared
CPaymentGateway is not bound in the service container
DThe namespace declaration is incorrect
Attempts:
2 left
💡 Hint
Check if the service container knows how to create PaymentGateway.
🧠 Conceptual
expert
2:00remaining
What is the main benefit of using dependency injection in Laravel controllers?
Choose the best explanation for why dependency injection is used in Laravel controllers.
AIt prevents the use of service providers
BIt forces all dependencies to be global singletons
CIt makes controllers run faster by caching dependencies
DIt allows automatic resolution and easier testing by decoupling dependencies
Attempts:
2 left
💡 Hint
Think about how dependency injection affects code flexibility and testing.

Practice

(1/5)
1. What is the main purpose of dependency injection in Laravel controllers?
easy
A. To automatically provide required objects to the controller
B. To manually create objects inside controller methods
C. To make controllers dependent on global variables
D. To avoid using any external classes in controllers

Solution

  1. Step 1: Understand dependency injection concept

    Dependency injection means Laravel automatically gives the controller the objects it needs without manual creation.
  2. Step 2: Identify the purpose in Laravel controllers

    This keeps controllers clean and easy to test by providing dependencies automatically.
  3. Final Answer:

    To automatically provide required objects to the controller -> Option A
  4. Quick Check:

    Dependency injection = automatic object provision [OK]
Hint: Dependency injection means Laravel gives needed objects automatically [OK]
Common Mistakes:
  • Thinking you must create objects manually inside controllers
  • Confusing dependency injection with global variables
  • Believing dependency injection removes use of external classes
2. Which of the following is the correct way to inject a service into a Laravel controller constructor?
easy
A. public function __construct($service) { $this->service = new Service(); }
B. public function __construct(Service $service) { $this->service = $service; }
C. public function __construct() { $this->service = Service::class; }
D. public function __construct(Service $service) { $service = new Service(); }

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    public function __construct(Service $service) { $this->service = $service; } -> Option B
  4. Quick Check:

    Constructor injection = type hint + assign property [OK]
Hint: 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
3. Given this controller method, what will be the output if the injected service returns 'Hello' from its greet() method?
public function show(Service $service) {
    return $service->greet();
}
medium
A. "Hello"
B. Error: Service not found
C. null
D. "greet"

Solution

  1. Step 1: Understand method injection

    The Service object is injected automatically into the show method by Laravel.
  2. Step 2: Call the greet() method on the injected service

    The greet() method returns the string "Hello", so the method returns "Hello".
  3. Final Answer:

    "Hello" -> Option A
  4. Quick Check:

    Injected service method output = "Hello" [OK]
Hint: Injected method returns service method result directly [OK]
Common Mistakes:
  • Assuming service is not injected and causes error
  • Expecting method name instead of method return value
  • Confusing null with empty string output
4. What is wrong with this controller constructor for dependency injection?
public function __construct(Service $service) {
    $service = new Service();
    $this->service = $service;
}
medium
A. It lacks type hinting for the service parameter
B. It does not assign the service to a class property
C. It creates a new Service instance instead of using the injected one
D. It should not use $this keyword inside constructor

Solution

  1. Step 1: Analyze the constructor parameter and assignment

    The constructor receives a Service object but immediately overwrites it by creating a new instance.
  2. Step 2: Understand why this is wrong

    This defeats dependency injection because the injected object is ignored and a new one is created manually.
  3. Final Answer:

    It creates a new Service instance instead of using the injected one -> Option C
  4. Quick Check:

    Overwriting injected service = wrong [OK]
Hint: Do not create new instance; use injected object directly [OK]
Common Mistakes:
  • Overwriting injected parameter with new instance
  • Forgetting to assign injected object to property
  • Confusing type hinting with variable assignment
5. You want to inject two services, Logger and Mailer, into a Laravel controller and use them in a method. Which constructor and method setup is correct?
hard
A. public function __construct() { $this->logger = new Logger(); $this->mailer = new Mailer(); } public function notify() { $this->logger->log('Notify'); $this->mailer->send(); }
B. public function __construct(Mailer $mailer) { $this->mailer = $mailer; } public function notify(Logger $logger) { $logger->log('Notify'); }
C. public function __construct(Logger $logger) { $this->logger = $logger; } public function notify(Mailer $mailer) { $mailer->send(); }
D. public function __construct(Logger $logger, Mailer $mailer) { $this->logger = $logger; $this->mailer = $mailer; } public function notify() { $this->logger->log('Notify'); $this->mailer->send(); }

Solution

  1. Step 1: Check constructor injection of both services

    public function __construct(Logger $logger, Mailer $mailer) { $this->logger = $logger; $this->mailer = $mailer; } public function notify() { $this->logger->log('Notify'); $this->mailer->send(); } correctly injects both Logger and Mailer in the constructor and assigns them to properties.
  2. Step 2: Verify method usage of injected services

    The notify method uses the injected properties to call log and send methods, which is correct.
  3. Final Answer:

    public function __construct(Logger $logger, Mailer $mailer) { $this->logger = $logger; $this->mailer = $mailer; } public function notify() { $this->logger->log('Notify'); $this->mailer->send(); } -> Option D
  4. Quick Check:

    Inject all services in constructor, use properties in methods [OK]
Hint: Inject all services in constructor, use $this->property in methods [OK]
Common Mistakes:
  • Injecting services only in methods instead of constructor
  • Creating new instances inside constructor instead of injecting
  • Mixing constructor and method injection inconsistently
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard