Dependency Injection in Laravel Controllers
Your invoice controller now needs to calculate GST. The first idea is simple: write $amount * 0.18 inside the method. Then the same calculation is needed in the summary page, in the invoice email and in the PDF. You copy the formula to four places. When the rate or the rounding rule changes, you will find three of them and miss one.
The natural fix is to move the calculation into its own class and use it wherever it is needed. But then a new question appears. Who creates that class? If every controller writes new GstCalculator() by hand, the controller becomes tightly tied to that exact class, and replacing it later becomes painful.
Laravel has a neat answer: you simply declare what your controller needs, and Laravel delivers it. This is called dependency injection, and in this lesson you will learn how it works in controllers.
The Problem with Creating Objects Yourself
First, the shared class. Create app/Services/GstCalculator.php. The next lesson explains how to organize folders like Services, so for now just create the file:
<?php
namespace App\Services;
class GstCalculator
{
public function gst(int|float $amount): float
{
return $amount * 0.18;
}
public function total(int|float $amount): float
{
return $amount + $this->gst($amount);
}
}
Now the bad way to use it in a controller, where the controller builds the object itself:
public function show(int $invoice)
{
$calculator = new GstCalculator();
$data = $this->invoices()[$invoice] ?? abort(404);
return [
'invoice' => $invoice,
'amount' => $data['amount'],
'gst' => $calculator->gst($data['amount']),
'total' => $calculator->total($data['amount']),
];
}
This works, but it has hidden problems:
- The dependency is buried inside the method, so you cannot see what the class needs without reading all of it
- If
GstCalculatorlater needs constructor arguments, you must update everynewcall - You cannot easily swap it for a different class, for example a fake one in a test
- Every controller repeats the same object creation code
What Is Dependency Injection?
A dependency is any object your class needs to do its job. Here, InvoiceController depends on GstCalculator. Injection means the object is handed to your class from outside, instead of the class creating it itself.
Think of a restaurant kitchen. A chef does not go out to the market for vegetables in the middle of cooking. The ingredients are placed on the counter, and the chef simply uses them. The chef states what is needed, and someone else supplies it.
In Laravel, the supplier is the service container, which you studied in the Service Container & Service Providers lesson. Here is how it behaves when a request reaches a controller:
Request --> Router finds InvoiceController::show
|
Container reads the constructor
"this controller needs a GstCalculator"
|
Container creates GstCalculator
and passes it into the controller
|
Container reads show()
"this method needs an int named $invoice"
and takes it from the URL
|
show(1001) runs and returns the response
The container finds out what your class needs by reading the type hints, which are the class names you write before each argument. This means you only have to write the type hint. There is nothing to register for a simple class like GstCalculator.
Constructor Injection
Constructor injection means you list your dependencies in the __construct method. The container passes them in when it creates the controller:
<?php
namespace App\Http\Controllers;
use App\Services\GstCalculator;
class InvoiceController extends Controller
{
public function __construct(private GstCalculator $gst)
{
}
public function show(int $invoice)
{
$data = $this->invoices()[$invoice] ?? abort(404);
return [
'invoice' => $invoice,
'amount' => $data['amount'],
'gst' => $this->gst->gst($data['amount']),
'total' => $this->gst->total($data['amount']),
];
}
// index(), create() and the other methods stay the same
}
The words private GstCalculator $gst do two jobs at once. They declare the argument, and PHP’s constructor promotion turns it into a property of the class, so every method can use $this->gst.
You never write new InvoiceController(...) anywhere. Laravel builds the controller, sees the type hint, builds GstCalculator and passes it in. The dependency is now visible at the top of the class, and the method is shorter than before.
Method Injection
Sometimes only one method needs a dependency. Instead of putting it in the constructor, you can type-hint it directly in that method:
public function summary(GstCalculator $gst)
{
$subtotal = 12500 + 8400 + 21000;
return [
'subtotal' => $subtotal,
'gst' => $gst->gst($subtotal),
'total' => $gst->total($subtotal),
];
}
The container reads the method’s arguments just as it reads the constructor’s. You have been using method injection since the first controller lesson, even if you did not notice it. The Request $request argument in store() and update() is a class that Laravel created and injected for you.
Mixing Dependencies with Route Parameters
A method can receive injected classes and route values together:
public function update(Request $request, GstCalculator $gst, int $invoice)
{
$total = $gst->total(12500);
return "Invoice {$invoice} updated. New total: {$total}";
}
Laravel knows that Request and GstCalculator are classes, so it creates them. The int $invoice is a plain value, so it comes from the URL. A common habit is to list injected classes first and route parameters last, which keeps the signature easy to read.
Invokable Controllers
Everything above also works in the single action controllers from the previous lesson. You can inject into the constructor or directly into __invoke:
class InvoiceSummary extends Controller
{
public function __invoke(GstCalculator $gst)
{
$subtotal = 12500 + 8400 + 21000;
return [
'subtotal' => $subtotal,
'gst' => $gst->gst($subtotal),
'total' => $gst->total($subtotal),
];
}
}
Constructor or Method Injection?
Both styles give you the same result, so choose by how widely the dependency is used:
- Use the constructor when most methods in the controller need the same dependency, like
GstCalculatorinInvoiceController - Use a method argument when only one action needs it, so other actions do not carry something they do not use
- Always use a method argument for the
Requestobject, since each request is different
If you find the constructor growing to five or six dependencies, the controller is probably doing too much. That is a signal to move work out of it, which is the topic of the next lesson.
Injecting Interfaces
So far we injected a concrete class. The real power of injection appears when you inject an interface. An interface describes what something can do, without saying how.
Suppose your app takes payments through Razorpay today, but a client may ask for another provider tomorrow. Write the contract first:
<?php
namespace App\Contracts;
interface PaymentGateway
{
public function createOrder(int $amountInPaise): string;
}
Then a class that follows it:
<?php
namespace App\Services;
use App\Contracts\PaymentGateway;
class RazorpayGateway implements PaymentGateway
{
public function createOrder(int $amountInPaise): string
{
// Later: call the Razorpay API here
return 'order_demo_' . $amountInPaise;
}
}
The controller asks only for the interface:
<?php
namespace App\Http\Controllers;
use App\Contracts\PaymentGateway;
class PaymentController extends Controller
{
public function __construct(private PaymentGateway $gateway)
{
}
public function create()
{
return $this->gateway->createOrder(1250000);
}
}
An interface cannot be created directly, so you must tell the container which class to use. You do this once, in the register() method of app/Providers/AppServiceProvider.php, which Laravel loads through bootstrap/providers.php:
use App\Contracts\PaymentGateway;
use App\Services\RazorpayGateway;
public function register(): void
{
$this->app->bind(PaymentGateway::class, RazorpayGateway::class);
}
Now the controller never mentions Razorpay. Switching to another provider means writing a new class and changing this one line. In the Testing chapter you will also use this idea to replace the real gateway with a fake one, so your tests never charge a real card.
Common Mistakes
Mistake 1: Creating the Object with new
$calculator = new GstCalculator();
PHP shows no error, so this mistake is quiet. But it brings back every problem from the start of the lesson: hidden dependencies, repeated setup and no way to replace the class. If a class is written by you and belongs to your app, inject it instead.
Mistake 2: Forgetting the Type Hint
public function summary($gst)
{
return $gst->total(12500);
}
Without a class name, the container has no idea what to put in $gst. You get:
Illuminate\Contracts\Container\BindingResolutionException: Unable to resolve dependency [Parameter #0 [ <required> $gst ]] in class App\Http\Controllers\InvoiceController
Add the class name in front of the variable: GstCalculator $gst.
Mistake 3: Injecting an Interface Without a Binding
If you type-hint PaymentGateway but never bind it in a service provider, Laravel cannot choose a class and fails:
Illuminate\Contracts\Container\BindingResolutionException: Target [App\Contracts\PaymentGateway] is not instantiable while building [App\Http\Controllers\PaymentController].
Add the bind() line in AppServiceProvider, as shown in the previous section.
Mistake 4: A Class That Needs a Plain Value
class RazorpayClient
{
public function __construct(private string $apiKey)
{
}
}
The container can build classes, but it cannot guess a text value like an API key:
Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [Parameter #0 [ <required> string $apiKey ]] in class App\Services\RazorpayClient
Give the argument a default value, or tell the container how to build the class inside a service provider. Keys and secrets should come from your .env file, which you will study in the Environment Configuration lesson.
Mistake 5: Injecting Too Much
If a constructor takes six or seven classes, the controller has grown into a place where everything happens. Injection makes this easy to see, which is a good thing. Treat a long list of dependencies as a hint to split the work.
Mistake 6: Putting Logic in the Constructor
The constructor should only receive dependencies. Do not run queries or send emails there, because the container creates the controller on every request that reaches it. Put real work in the action methods.
Quick Summary
- A dependency is an object your class needs, and injection means Laravel hands it over instead of the class creating it.
- The container reads your type hints and builds the right classes automatically.
- Constructor injection suits dependencies used by many methods, and method injection suits a single action.
- The
Requestobject you already use instore()is injected the same way. - Injected classes and route values can be mixed in one method, and route values are taken from the URL.
- Invokable controllers can use injection in the constructor or in
__invoke. - Concrete classes need no registration, while interfaces need a
bind()call in a service provider. - Avoid
newfor classes you own, because it hides dependencies and blocks replacement. - A very long constructor means the controller is doing too much.
What’s Next
You now know how a controller receives the classes it needs. The next question is where those classes should live and what should move out of the controller in the first place. In the next lesson, Keeping Controllers Thin: Services & Folder Organization, you will learn how to organize your app so that controllers only coordinate, and the real work sits in well-named classes.