Laravel Service Providers: What They Are Actually For

Laravel Service Providers: What They Are Actually For

October 6, 2026
Laravel's two-pass boot: register on every provider, then boot on every provider.

Open AppServiceProvider in a codebase that has been running for two years and you will usually find a pagination view override, a Carbon locale, three macros, a Schema::defaultStringLength left over from a MySQL 5.7 migration, and a database listener someone added to debug a slow page and never removed.

That is not a criticism of anyone. It is what happens when a file is described as “where you bootstrap your application” and nothing further. The framework is quite specific about what belongs where; the specificity is just not obvious from the outside.

What a provider actually is

A provider is a class with two methods that Laravel calls in two distinct phases of the boot sequence. That is the entire concept. Everything else follows from the fact that the phases are separate and run in a fixed order.

class PaymentServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // phase 1: tell the container how to build things
    }

    public function boot(): void
    {
        // phase 2: everything is registered, now do things
    }
}

Laravel walks the provider list and calls register() on every single one. Only when that pass is finished does it go back and call boot() on every one. Two complete passes, never interleaved.

Laravel's two-pass boot: register on every provider, then boot on every provider.
Two complete passes, never interleaved — that guarantee is the whole design

Why the split exists

If there were a single method, provider A’s setup could run before provider B had said how its services are built — and A would then resolve B’s service from an empty container. The guarantee “by the time any boot() runs, every binding exists” is what makes providers composable, and it is the reason the framework insists on the split rather than offering it as a convenience.

Which gives a rule you can apply without thinking about it:

Never resolve anything out of the container inside register(). If you need something, you are in the wrong method.

The failure this prevents is not a clean error. Resolving too early often works — the service you wanted happened to be registered by a provider earlier in the list — and then breaks when somebody reorders the array or installs a package that registers itself first. A bug that appears on composer update and has nothing to do with the updated package is almost always this.

register(): bindings, and nothing else

public function register(): void
{
    // a new instance every time it is asked for
    $this->app->bind(InvoiceNumberGenerator::class, SequentialInvoiceNumbers::class);

    // one instance for the whole request
    $this->app->singleton(PaymentGateway::class, function ($app) {
        return new RazorpayGateway(
            config('services.razorpay.key'),
            config('services.razorpay.secret'),
        );
    });

    // merge package config so the app's published copy wins
    $this->mergeConfigFrom(__DIR__ . '/../config/payments.php', 'payments');
}

The interface binding is the one worth doing deliberately. Type-hint PaymentGateway in a controller, bind the concrete class here, and swapping the implementation for tests — or for a second gateway in a different region — is a one-line change in one file rather than a search across the codebase.

mergeConfigFrom is safe in register() because it touches the config repository, which exists before any provider runs. It is the exception that proves the rule: config is available early precisely so that bindings can read it.

Note what the closure does not do — it does not call the gateway, open a connection or read the database. It describes how to build the object. The closure runs later, the first time something actually asks for a PaymentGateway, and for many requests that is never.

boot(): everything that observes or extends

public function boot(): void
{
    Invoice::observe(InvoiceObserver::class);

    Gate::policy(Invoice::class, InvoicePolicy::class);

    Validator::extend('gstin', function ($attr, $value) {
        return (bool) preg_match('/^d{2}[A-Z]{5}d{4}[A-Z]dZ[A-Zd]$/', (string) $value);
    });

    Blade::directive('money', fn ($expr) => "<?php echo number_format($expr, 2); ?>");

    Route::bind('invoice_number', fn ($value) => Invoice::where('number', $value)->firstOrFail());
}

The common thread: each of these needs some other part of the framework to already exist. A policy needs the gate. A validator extension needs the validation factory. A route binding needs the router. Put any of them in register() and you are depending on boot order you do not control.

Deferred providers, and the boot time nobody measures

Every provider in the list gets both methods called on every request, including the ones for features this particular request will never touch. A PDF generator, a payment gateway, an SMS client — all registered on a request that renders the login page.

Registering a binding is cheap. Deferring is still worth doing, because the point is not the binding itself but everything a provider tends to accumulate around it.

class PdfServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register(): void
    {
        $this->app->singleton(PdfRenderer::class, fn () => new PdfRenderer(config('pdf')));
    }

    public function provides(): array
    {
        return [PdfRenderer::class];
    }
}

Laravel writes a manifest mapping each deferred binding to its provider. The provider is then not loaded at all until something resolves PdfRenderer, at which point it is registered and booted on the spot.

Two conditions, and both are easy to get wrong. The provider must have no boot() work that needs to happen unconditionally — a deferred provider whose boot() registers an event listener will simply never register it on requests that do not resolve the binding, which is a silent failure rather than an error. And provides() must list every binding, because one left out is a binding the container cannot resolve at all.

Conditions a provider must meet before it can be deferred.
Two conditions, and the first one fails silently when you get it wrong

Package discovery, and the provider you did not add

config/app.php lists your own providers. Most of the ones actually running are not there — packages declare themselves in their composer.json:

"extra": {
    "laravel": {
        "providers": ["Vendor\Package\PackageServiceProvider"],
        "aliases": {"Package": "Vendor\Package\Facades\Package"}
    }
}

Composer’s post-autoload hook writes these into bootstrap/cache/packages.php. That file is the real answer to “what is actually loaded”, and it is the first place to look when something is behaving as though a package is configured when you never configured it.

Discovery can be declined per package, which is occasionally the fix for a package that registers a route or a middleware you do not want:

"extra": {"laravel": {"dont-discover": ["vendor/package"]}}

Then register its provider yourself in config/app.php, minus whatever you were trying to avoid — or do not register it and resolve the class directly.

Breaking up the junk drawer

The practical version of all this is: AppServiceProvider should be short, and the way to make it short is to name things.

AppProviders
    AppServiceProvider.php          // genuinely app-wide, and small
    AuthServiceProvider.php         // policies and gate definitions
    EventServiceProvider.php        // listeners
    RouteServiceProvider.php        // route files, rate limiters, bindings
    PaymentServiceProvider.php      // the payment gateway and its config
    MacroServiceProvider.php        // collection, string and query macros

Five small providers cost nothing at runtime and mean that a developer looking for where payments are wired up opens a file called PaymentServiceProvider. In a single 200-line AppServiceProvider, the same developer reads all 200 lines.

The macro provider is worth separating specifically. Macros are invisible — a call to $collection->toCsv() has no definition to jump to — and having exactly one file where all of them live is the only thing that makes them discoverable.

Conditional registration, carefully

It is tempting to branch on the environment, and there is one sound use and one that causes trouble.

public function boot(): void
{
    if ($this->app->isLocal()) {
        $this->app->register(TelescopeServiceProvider::class);
    }

    if (! $this->app->isProduction()) {
        Model::preventLazyLoading();       // loud in dev, silent in prod
    }
}

Developer tooling is the sound case. Swapping business behaviour by environment is the one to avoid: a binding that resolves to a fake payment gateway outside production means the code path you test is not the code path that runs, and the first time you find out is in production. Prefer binding the real class everywhere and swapping it explicitly in the tests that need it.

One more thing that bites people: php artisan config:cache serialises the config, and a config file containing a closure cannot be serialised. The error message points at the cache command rather than at the file, so it is worth knowing that a provider reading config is fine and a config file holding a closure is not.

Which method each kind of setup belongs in.
Almost every provider bug is something in the wrong one of these two columns

Providers in tests, and the swap that actually works

The reason to bind an interface is so that tests can replace the implementation. The mechanics are worth getting right, because there are three ways to do it and they behave differently.

// 1. Rebind before the request — the usual one
$this->app->instance(PaymentGateway::class, new FakeGateway);

// 2. A mock the test asserts against
$this->mock(PaymentGateway::class, function ($mock) {
    $mock->shouldReceive('charge')->once()->andReturn(new Receipt('pay_123'));
});

// 3. A provider of your own, registered for the test environment only
$this->app->register(TestPaymentServiceProvider::class);

The first two are the ones to reach for. The third exists and is usually a mistake for business services, for the reason given above: the wiring under test stops being the wiring that ships.

The detail that trips people is timing. In a feature test, the application has already booted by the time your test method runs, so rebinding works for anything resolved during the request you are about to make — but not for something a provider’s boot() already grabbed and stored. If a provider does $this->app->make(PaymentGateway::class) in boot() and holds the result, no later rebind can reach it. That is another argument for the rule about resolving early: it also makes the code untestable, not just fragile.

Reading the provider list on a real app

When something is behaving strangely and you suspect a provider, there are three commands that answer it faster than reading files.

php artisan about                    # framework, cache and package summary
cat bootstrap/cache/packages.php     # every auto-discovered provider and alias
cat bootstrap/cache/services.php     # the deferred-binding manifest

packages.php is the honest list of what discovery added. services.php shows which bindings are deferred and to which provider, which is how you confirm a deferred provider is registered the way you think.

Both are caches. After changing a provider, php artisan clear-compiled and composer dump-autoload rebuild them — and a deployment that copies bootstrap/cache from a previous release is a good way to spend an afternoon debugging a provider change that did take effect locally. Those files belong in .gitignore and should be regenerated on the target, not shipped.

Facades, the container, and what a provider is really doing

It is worth closing the loop on facades, because they are the part of Laravel that looks like magic and is in fact the thinnest layer in the framework.

class Payments extends Facade
{
    protected static function getFacadeAccessor(): string
    {
        return PaymentGateway::class;
    }
}

// Payments::charge($invoice) is exactly:
// app(PaymentGateway::class)->charge($invoice)

That is the whole implementation. A facade is a static proxy that resolves a container binding and forwards the call — which means a facade without a provider binding its accessor throws a “target class does not exist” error, and the fix is always in a provider rather than in the facade.

It also explains why facades are testable at all. Payments::shouldReceive('charge') works by swapping the container binding underneath, which is the same mechanism as $this->mock(). Nothing static is being intercepted.

The practical consequence for provider design: bind to an interface, point the facade at the interface, and both the type-hinted and the facade call sites resolve the same object. Bind to a concrete class and the facade quietly hard-codes that choice for every caller who used it.

A provider for your own package

Once a provider is doing more than wiring — publishing config, loading migrations, registering commands — you are effectively writing a package, and the methods for that are already on the base class.

public function boot(): void
{
    $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
    $this->loadViewsFrom(__DIR__ . '/../resources/views', 'payments');
    $this->loadRoutesFrom(__DIR__ . '/../routes/payments.php');

    if ($this->app->runningInConsole()) {
        $this->publishes([
            __DIR__ . '/../config/payments.php' => config_path('payments.php'),
        ], 'payments-config');

        $this->commands([ReconcilePaymentsCommand::class]);
    }
}

The runningInConsole() guard is not decoration. publishes() and commands() only matter to Artisan, and running them on every web request is work for nothing. It is a small saving per request and it is free.

The pairing to remember is mergeConfigFrom in register() with publishes in boot(): the merge supplies defaults for anything the app has not overridden, the publish gives the app a copy to override. Do only the publish and a fresh install has no config at all until someone runs the publish command.

A provider that wires up a third-party client

The most common real-world provider is one that turns a vendor SDK into something the rest of the app can type-hint, and it is worth seeing whole because it uses most of what is above.

class SmsServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/sms.php', 'sms');

        $this->app->singleton(SmsClient::class, function ($app) {
            $c = $app['config']['sms'];

            return new Msg91Client(
                key:    $c['key'],
                sender: $c['sender'],
                route:  $c['route'],
                http:   $app->make(HttpFactory::class),
            );
        });

        $this->app->alias(SmsClient::class, 'sms');
    }

    public function provides(): array
    {
        return [SmsClient::class, 'sms'];
    }
}

Worth noticing what is happening inside the closure. It calls $app->make() — which looks like the thing the rule forbids — and it is fine, because the closure does not run during register(). It runs the first time somebody resolves SmsClient, which is long after both passes have finished. The rule is about code that executes in register(), not code that is defined there.

The alias is there so both app('sms') and the class name resolve to the same singleton, and it is listed in provides() for the same reason every other binding must be: a deferred provider is invisible until one of its declared bindings is asked for.

Reading config through $app['config'] rather than the config() helper is a small habit worth having in providers. It is the same repository, but it makes the dependency explicit, and it keeps working if the closure is ever moved somewhere the helpers are not bootstrapped.

The mental model

Two passes over the provider list. The first says how things are built and resolves nothing. The second does the work, and by then everything exists.

Almost every provider bug is a violation of that sentence — something resolved in register(), something extended in register(), or a deferred provider with boot() work that quietly never runs. Once the split is the thing you check first, the file stops being a junk drawer and becomes the place the application’s wiring is written down.