Laravel Service Container & Service Providers Explained
Open any Laravel controller and you will notice something that looks like magic. A method asks for a Request, a Mailer, or your own PaymentGateway, and Laravel simply hands it over. Nobody wrote new anywhere.
That is not magic. It is the Service Container doing its job, and Service Providers are how you teach it what to build.
In the Request Lifecycle lesson, you saw that Laravel boots service providers before any request logic runs. This lesson explains what those providers actually do, and why understanding the container makes your code cleaner, easier to test, and easier to change later.
The Problem: Classes That Build Their Own Dependencies
Imagine you are building a checkout feature. A beginner-friendly version of the controller might look like this:
class OrderController extends Controller
{
public function store(Request $request)
{
// The controller creates its own dependency
$gateway = new RazorpayGateway('rzp_live_key', 'rzp_live_secret');
$gateway->charge($request->integer('amount'));
return redirect('/orders')->with('success', 'Payment received.');
}
}
This works, but it has real problems:
- The controller is tightly coupled to Razorpay. Switching to another provider means editing every place that says
new RazorpayGateway. - API keys are hard-coded inside the controller.
- You cannot test the controller without making a real payment call.
- If ten controllers need the gateway, you repeat the same setup ten times.
The fix is simple in principle: a class should ask for what it needs instead of building it. The Service Container is the tool that makes this practical.
What Is the Service Container?
The Service Container is Laravel’s built-in tool for creating classes and managing their dependencies. Think of it as a smart factory with a registry:
- You tell it how to build certain things, or it figures it out on its own.
- When any part of your app asks for one of those things, the container builds it and hands it over, along with everything that thing needs.
Handing dependencies to a class from the outside is called dependency injection, and the container performs it automatically. You have already met the container: the application object created in bootstrap/app.php is the container.
Automatic Resolution: Zero Configuration
For most classes, you do not have to configure anything. If a class has no special requirements, Laravel reads the type-hints in its constructor and builds it for you.
// app/Services/InvoiceCalculator.php
class InvoiceCalculator
{
public function total(array $items): float
{
return collect($items)->sum(fn ($item) => $item['price'] * $item['qty']);
}
}
// app/Http/Controllers/InvoiceController.php
class InvoiceController extends Controller
{
// Laravel sees the type-hint and injects an InvoiceCalculator
public function __construct(private InvoiceCalculator $calculator) {}
public function show()
{
$total = $this->calculator->total([
['price' => 500, 'qty' => 2],
['price' => 250, 'qty' => 1],
]);
return view('invoices.show', compact('total'));
}
}
There is no binding, no registration, and no new. Laravel uses PHP Reflection to read the constructor, sees that it needs an InvoiceCalculator, creates one, and passes it in. If InvoiceCalculator needed other classes, the container would build those first, however deep the chain goes.
You can also inject into controller methods, not just constructors:
public function store(Request $request, InvoiceCalculator $calculator)
{
// Both $request and $calculator are injected
}
Injection inside controllers has its own lesson later in the course. Here, the focus is on how the container makes it possible.
When You Need to Bind Something
Automatic resolution only works when Laravel can work out how to build the class. It cannot in two common situations:
- The type-hint is an interface. An interface cannot be instantiated, so the container must be told which class to use.
- The constructor needs plain values like API keys or strings, which the container has no way to guess.
Our payment gateway has both problems. Let’s solve them step by step.
Step 1: Define an Interface
// app/Contracts/PaymentGateway.php
namespace App\Contracts;
interface PaymentGateway
{
public function charge(int $amountInPaise): bool;
}
Step 2: Write the Implementation
// app/Services/RazorpayGateway.php
namespace App\Services;
use App\Contracts\PaymentGateway;
class RazorpayGateway implements PaymentGateway
{
public function __construct(
private string $key,
private string $secret,
) {}
public function charge(int $amountInPaise): bool
{
// Call the Razorpay API here
return true;
}
}
Step 3: Bind It
Now tell the container: “whenever someone asks for PaymentGateway, build a RazorpayGateway with these credentials.” The credentials come from config, which reads from .env:
// config/services.php
'razorpay' => [
'key' => env('RAZORPAY_KEY'),
'secret' => env('RAZORPAY_SECRET'),
],
// app/Providers/AppServiceProvider.php
public function register(): void
{
$this->app->bind(PaymentGateway::class, function ($app) {
return new RazorpayGateway(
config('services.razorpay.key'),
config('services.razorpay.secret'),
);
});
}
Do not worry about where this code lives yet. The Service Provider section below explains it.
The controller now depends on the interface, not on Razorpay:
class OrderController extends Controller
{
public function store(Request $request, PaymentGateway $gateway)
{
$gateway->charge($request->integer('amount'));
return redirect('/orders')->with('success', 'Payment received.');
}
}
The controller no longer knows or cares which gateway it uses. To switch providers, you change one place:
$this->app->bind(PaymentGateway::class, fn ($app) => match (config('services.payment.driver')) {
'stripe' => new StripeGateway(config('services.stripe.secret')),
default => new RazorpayGateway(
config('services.razorpay.key'),
config('services.razorpay.secret'),
),
});
Not a single controller changes. This is the real payoff of the container.
bind() vs singleton()
There are two main ways to register a binding, and the difference matters:
// bind() - a NEW instance every time it is resolved
$this->app->bind(ReportBuilder::class, fn ($app) => new ReportBuilder());
// singleton() - created ONCE, then the same instance is reused
$this->app->singleton(ExchangeRateService::class, fn ($app) => new ExchangeRateService(
config('services.exchange.key')
));
Use singleton() for services that are expensive to create or that must share state, such as an API client. Use bind() when each consumer should get a fresh, independent object.
Laravel also has scoped(), which behaves like a singleton but resets between requests or queue jobs on long-running workers. You will rarely need it as a beginner.
Resolving Manually
Most of the time, constructor and method injection is all you need. But sometimes you are somewhere injection is not possible, like a helper function or a quick script. There you can ask the container directly:
$gateway = app(PaymentGateway::class); $gateway = resolve(PaymentGateway::class); $gateway = app()->make(PaymentGateway::class);
All three do the same thing. Prefer constructor injection wherever you can, because it shows a class’s dependencies at a glance. Reaching into the container from the middle of your code hides them.
Facades Are Shortcuts to the Container
You have probably seen code like Cache::get('key') or Mail::send(...). These are Facades: static-looking shortcuts that quietly pull the real object out of the container. Cache::get() resolves the cache manager from the container and calls get() on it. Facades are convenient, and they work because of the container underneath.
What Is a Service Provider?
The container needs to be told about your bindings somewhere. That somewhere is a Service Provider.
A Service Provider is a class whose job is to register services into the container and prepare the application. Laravel’s own features are set up this way: the database, cache, mail, queue, and authentication each have a provider inside the framework. Your application uses the same mechanism for its own services.
Every provider has two methods, and the difference between them is the most important idea in this lesson.
register() vs boot()
namespace App\Providers;
use App\Services\ExchangeRateService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bind things into the container.
*/
public function register(): void
{
$this->app->singleton(ExchangeRateService::class, fn ($app) => new ExchangeRateService(
config('services.exchange.key')
));
}
/**
* Run code after ALL providers have been registered.
*/
public function boot(): void
{
// Force HTTPS links in production
if ($this->app->isProduction()) {
URL::forceScheme('https');
}
// Catch N+1 query problems during development
Model::preventLazyLoading(! $this->app->isProduction());
}
}
The rule is simple:
- register() is only for binding things into the container. Nothing else.
- boot() is for everything that uses services: setting defaults, registering view composers, defining rate limiters, and similar setup.
Why the split? Laravel calls register() on every provider first, and only then calls boot() on each one. By the time boot() runs, every binding in the app already exists, so you can safely use any service. If you used a service inside register(), the provider that binds it might not have run yet.
Where Providers Live in Laravel 11+
In Laravel 10 and older, providers were listed in a providers array inside config/app.php, and a fresh project came with several of them, such as RouteServiceProvider and EventServiceProvider.
Modern Laravel is much leaner. A new project has just one provider, and the list lives in bootstrap/providers.php:
<?php
return [
App\Providers\AppServiceProvider::class,
];
The old providers are gone because their jobs are handled elsewhere. Routing and middleware are configured in bootstrap/app.php, and events and policies are discovered automatically. For many applications, AppServiceProvider is the only provider you will ever need.
Creating Your Own Provider
As an app grows, putting every binding in AppServiceProvider gets messy. You can group related bindings into their own provider:
php artisan make:provider PaymentServiceProvider
In Laravel 11+, this command creates app/Providers/PaymentServiceProvider.php and automatically adds it to bootstrap/providers.php. If you create a provider class by hand, you must add it to that file yourself, or Laravel will never load it.
namespace App\Providers;
use App\Contracts\PaymentGateway;
use App\Services\RazorpayGateway;
use Illuminate\Support\ServiceProvider;
class PaymentServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(PaymentGateway::class, fn ($app) => new RazorpayGateway(
config('services.razorpay.key'),
config('services.razorpay.secret'),
));
}
}
Now all payment wiring lives in one named, easy-to-find place.
For simple cases where a class needs nothing special in its constructor, you can skip the closure and use the $bindings and $singletons properties:
class ReportServiceProvider extends ServiceProvider
{
public array $bindings = [
ReportExporter::class => CsvReportExporter::class,
];
public array $singletons = [
ReportCache::class => ReportCache::class,
];
}
This does not work for RazorpayGateway, because its constructor needs the key and secret strings. Those cases need a closure.
Two Advanced Options to Know About
Contextual binding lets two classes receive different implementations of the same interface:
$this->app->when(AdminReportController::class)
->needs(PaymentGateway::class)
->give(fn () => new StripeGateway(config('services.stripe.secret')));
Everywhere else still gets Razorpay. Only AdminReportController receives Stripe.
Deferred providers load only when one of their services is actually requested, instead of on every request. A provider implements DeferrableProvider and lists its services in a provides() method. It can only contain register() logic, so you will rarely need this early on.
How This Fits the Request Lifecycle
In the Request Lifecycle lesson, one step was “Service Providers boot the application.” Now you know what that means:
1. Laravel creates the container 2. register() runs on every provider -> bindings are added 3. boot() runs on every provider -> setup code runs 4. Middleware, routing and your controller run, with every service ready to inject
On a standard Nginx and PHP-FPM setup, this whole process happens on every request. That is why boot() should stay light: a database query or API call inside it runs on every page load. Long-running servers like Laravel Octane boot the application once per worker instead, but keeping providers lightweight is good practice either way.
Why This Makes Testing Easy
Because the controller depends on an interface, swapping the real service for a fake one in a test takes a single line:
$this->app->bind(PaymentGateway::class, fn () => new FakePaymentGateway());
Your tests never touch Razorpay, run instantly, and cannot charge anyone by accident. You will use this idea in the Testing chapter.
Common Mistakes
Mistake 1: Using new Inside Controllers
// Avoid
$gateway = new RazorpayGateway($key, $secret);
// Prefer
public function store(Request $request, PaymentGateway $gateway) { ... }
Every new for a service is a hard-coded dependency you will have to hunt down later.
Mistake 2: Using Other Services Inside register()
register() runs before every provider has finished registering. Using a service that another provider binds, or calling something like Cache::get() there, can fail or behave unpredictably. Move that code into boot().
Mistake 3: Heavy Work Inside boot()
Queries, HTTP calls, and file reads inside boot() slow down every request. Keep boot() for lightweight setup only.
Mistake 4: Forgetting to Register a Provider
If you hand-create a provider and none of its bindings work, check bootstrap/providers.php. Providers made with php artisan make:provider are added automatically, but manually created ones are not.
Mistake 5: Forgetting to Bind an Interface
If you see this error:
Target [App\Contracts\PaymentGateway] is not instantiable.
Laravel was asked for an interface and has no binding that says which class to use. Add the binding in a provider’s register() method.
A related error looks like this:
Unresolvable dependency resolving [Parameter #0 [ <required> string $key ]] in class App\Services\RazorpayGateway
The container tried to build the class automatically but cannot guess plain values like strings. Bind the class with a closure and supply the values.
Mistake 6: Calling app() Everywhere
Pulling services out with app(Something::class) deep inside your code works, but it hides dependencies and makes testing harder. Treat it as a fallback, not the default.
Quick Summary
- The Service Container builds classes and injects their dependencies automatically.
- Most classes need no configuration. Laravel reads constructor type-hints and does the rest.
- You bind when the type-hint is an interface or the constructor needs plain values.
- Use
bind()for a fresh instance every time andsingleton()to reuse one instance. - Service Providers are where bindings and startup code live.
register()only binds things.boot()uses them.- In Laravel 11+, providers are listed in
bootstrap/providers.php, and a new project has onlyAppServiceProvider. - Depending on interfaces instead of concrete classes keeps your code flexible and easy to test.
What’s Next
You now understand how a Laravel application is put together, from folders and MVC to the request lifecycle and the container that wires everything. The foundations are done. In the next chapter, you will start building with Routing, where you define URLs, pass parameters, and send requests to the right controllers.