AppServiceProvider exists in every fresh Laravel application, which makes it
an attractive drawer for anything that lacks an obvious home. A macro goes in.
Then an HTTP client, a model setting, an event callback, package configuration,
and an eager app()->make() call. At that point startup failures become hard to
reason about: a provider resolves a service before another one has bound it, a
test boots a partial application, or configuration behaves differently after
config:cache.
Service providers are not a miscellaneous hook. They are composition roots: the place where Laravel learns how the application's concrete collaborators fit together and where a package extends the framework. Their two lifecycle methods have intentionally different jobs:
register()describes bindings and configuration defaults without depending on the whole application being ready.boot()runs after Laravel has calledregister()for all configured providers. It may receive dependencies through method injection and attach behaviour that requires the completed graph.
We will build a small invoice-delivery integration, follow it through both phases, and decide whether it should be deferred. The goal is not a mnemonic; it is predictable application startup in production and tests.
The boundary is dependency order
Laravel constructs the configured providers and calls register() on all of
them before calling any provider's boot() method. Therefore a binding from
PaymentsServiceProvider is available in another provider's boot(), but it
is unsafe to assume it exists while a different register() call is running.
This provider looks innocent, yet it resolves a service while registration is
still underway. If a package provider has not bound InvoiceSender yet, the
result is either an exception or an accidental auto-wired concrete class. In
both cases, provider order becomes hidden application behaviour.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\InvoiceSender;
use Illuminate\Support\ServiceProvider;
final class BrokenBillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$sender = $this->app->make(InvoiceSender::class);
$sender->warmUp();
}
}
Do not repair this by putting the provider higher in bootstrap/providers.php.
That is the modern location for application providers, but ordering is a poor
replacement for an explicit boundary. Register a recipe first; resolve it after
the application has finished registration.
Build a small service, then compose it
Start with a contract that says what the application needs, rather than naming a vendor SDK. The provider composes objects; the sender owns delivery.
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Models\Invoice;
interface InvoiceSender
{
public function send(Invoice $invoice): void;
}
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Models\Invoice;
use Illuminate\Contracts\Mail\Mailer;
final class MailInvoiceSender implements InvoiceSender
{
public function __construct(
private readonly Mailer $mailer,
private readonly string $fromAddress,
) {
}
public function send(Invoice $invoice): void
{
$this->mailer->raw(
"Invoice #{$invoice->getKey()} is ready.",
function ($message) use ($invoice): void {
$message->from($this->fromAddress)
->to($invoice->customer->email)
->subject("Invoice #{$invoice->getKey()}");
},
);
}
}
Configuration enters through the constructor. The class does not call env()
or reach into the global container. Environment lookups belong in config files;
after config:cache, direct env() calls outside config/*.php are not a
reliable runtime configuration source.
<?php
return [
'from_address' => env('BILLING_FROM_ADDRESS', '[email protected]'),
];
register() can now bind the contract. The closure is a recipe, not an eager
instruction to create MailInvoiceSender. Laravel runs it only when a caller
requests InvoiceSender.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\InvoiceSender;
use App\Billing\MailInvoiceSender;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(
InvoiceSender::class,
function (Application $app): InvoiceSender {
return new MailInvoiceSender(
mailer: $app->make('mailer'),
fromAddress: (string) config('billing.from_address'),
);
},
);
}
}
For a plain interface-to-class mapping, keep it even simpler:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\InvoiceSender;
use App\Billing\MailInvoiceSender;
use Illuminate\Support\ServiceProvider;
final class SimpleBillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(InvoiceSender::class, MailInvoiceSender::class);
}
}
Use a closure only for real composition: configuration, a factory, or an explicit conditional. Autowiring is easier to inspect and just as easy to mock.
register() is declarative plumbing
Good register() work is limited to container bindings, singletons,
configuration defaults, and package facilities that describe resources. In a
package, mergeConfigFrom() supplies defaults for missing consumer keys;
publishing provides a copy the consumer can edit. Those are different jobs.
<?php
declare(strict_types=1);
namespace Acme\Billing\Providers;
use Acme\Billing\InvoiceSender;
use Acme\Billing\MailInvoiceSender;
use Illuminate\Support\ServiceProvider;
final class BillingPackageServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(
__DIR__.'/../../config/billing.php',
'billing',
);
$this->app->singleton(InvoiceSender::class, MailInvoiceSender::class);
}
}
mergeConfigFrom() merges only the first level of an array. When a consumer
sets billing.mail, that nested array replaces the package value; missing
nested keys are not inherited. Prefer a flat config shape where this would be
surprising, explicitly merge nested options in a validated options object, or
use replaceConfigRecursivelyFrom() only when replacement semantics fit.
Avoid database queries, network calls, auth(), route inspection, and model
observers that immediately resolve other services in this phase. They give
every command, queue worker, test kernel, and cached bootstrap request-shaped
side effects before Laravel is ready to serve one.
boot() configures the completed graph
Use boot() for extension points that need all providers registered. Laravel
can inject a dependency into the method, which makes the requirement visible
without the app() helper. Here, a provider registers a response macro once the
framework's response factory is available.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Billing\InvoiceSender;
use App\Billing\MailInvoiceSender;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\ServiceProvider;
final class BillingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(InvoiceSender::class, MailInvoiceSender::class);
}
public function boot(ResponseFactory $response): void
{
$response->macro('acceptedJson', function (array $payload): JsonResponse {
return $this->json($payload, 202);
});
}
}
The injected response factory is a legal lifecycle dependency; it is not a
reason to instantiate every dependency in boot(). Avoid doing work merely to
prove an object can be resolved. For application domain events, prefer explicit
event classes and discovered listeners over a large provider registry. Listeners
related to a transaction should use after-commit dispatching rather than a
provider callback.
Packages commonly use boot() for routes, views, migrations, publish groups,
macros and validation extensions:
<?php
declare(strict_types=1);
namespace Acme\Billing\Providers;
use Illuminate\Support\ServiceProvider;
final class BillingPackageServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../../config/billing.php', 'billing');
}
public function boot(): void
{
$this->publishes([
__DIR__.'/../../config/billing.php' => config_path('billing.php'),
], 'billing-config');
$this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
}
}
Publishing is an explicit developer operation, not runtime deployment work. Merge defaults so a package works before publishing; publish only files the consumer should own.
Config cache changes the failure mode, not the rule
config:cache compiles configuration into one cached file. Providers still run
and a bad dependency in register() remains bad. What changes is the safety of
this runtime lookup:
<?php
declare(strict_types=1);
namespace App\Billing;
final class UnsafeBillingOptions
{
public function fromAddress(): string
{
return (string) env('BILLING_FROM_ADDRESS');
}
}
Put the environment lookup in config/billing.php; use config() at runtime.
For package code that reads configuration during boot, test the normal and
cached paths in CI. Otherwise, a deployment that builds the cache before new
environment values are available can retain old values until it is rebuilt.
Deferred providers postpone a service
DeferrableProvider lets Laravel skip a provider until a declared binding is
requested. It helps with expensive, optional package integrations on commands
that never use them. provides() is a strict promise: every abstract whose
resolution should load the provider must be listed.
<?php
declare(strict_types=1);
namespace Acme\Billing\Providers;
use Acme\Billing\InvoiceSender;
use Acme\Billing\MailInvoiceSender;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;
final class DeferredBillingServiceProvider extends ServiceProvider implements DeferrableProvider
{
public function register(): void
{
$this->app->singleton(InvoiceSender::class, MailInvoiceSender::class);
}
/**
* @return list<class-string>
*/
public function provides(): array
{
return [InvoiceSender::class];
}
}
Do not defer routes, event listeners, policy mappings, view namespaces, macros, or a binding used on nearly every request. That changes a lifecycle requirement into first-request latency or a failure. Measure startup cost and traffic first; removing unnecessary work is usually clearer than moving necessary work.
$this->app->booting() and $this->app->booted() are similarly narrow tools:
use them only for genuine framework coordination, and document why a middleware
or listener would not communicate the lifecycle better.
Test the composition root as wiring
Provider bugs are integration bugs: the wrong implementation is bound, a
default is missing, or a deferred service cannot resolve. Test through the
container, not by mocking a provider's internals. Orchestra Testbench provides
a Laravel application for a package; an application test can use app().
<?php
declare(strict_types=1);
use Acme\Billing\InvoiceSender;
use Acme\Billing\MailInvoiceSender;
use Acme\Billing\Providers\BillingPackageServiceProvider;
use Orchestra\Testbench\TestCase;
final class BillingPackageServiceProviderTest extends TestCase
{
public function test_it_binds_the_invoice_sender_contract(): void
{
$this->app->register(BillingPackageServiceProvider::class);
$sender = $this->app->make(InvoiceSender::class);
self::assertInstanceOf(MailInvoiceSender::class, $sender);
}
}
For a deferred provider, resolve every promised abstract. For configuration, set a consumer override and assert it wins over the package default. Static analysis cannot catch a correct class bound under the wrong key.
When not to use a service provider
Do not create one because a class has dependencies. Constructor injection already builds ordinary actions, jobs, controllers, listeners and commands. A provider earns its place when it changes application composition or extends the framework: binding an interface, decorating a client, exposing a package resource, or registering an extension point.
Avoid a provider for one business workflow. An ApproveInvoice action should
call its injected InvoiceSender, not hide work behind a boot-time closure.
Avoid it for per-request decisions too: middleware, policies, form requests and
listeners show their scope much better. The alternative is not no architecture;
it is behaviour beside the use case and a provider limited to composition.
Production pitfalls
- Resolving services or performing I/O in
register()couples boot order to side effects and taxes every command. env()outside config files appears to work locally and fails subtly after configuration is cached.- Treating
mergeConfigFrom()as recursive silently drops nested defaults. - A giant
AppServiceProvidermakes unrelated boot work difficult to test and delete; split by integration or module when a boundary is real. - Deferring an always-used service moves cost to the first request without removing it.
The lifecycle rule is short: describe the graph in register() and configure
the fully registered graph in boot(). Following it makes application startup
ordinary rather than magical.