Service Providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services (Router, Database, Queue, Mail, Broadcast), are bootstrapped via service providers. In this tutorial class, you will master the difference between register() and boot(), create custom providers, and discover how to package code into reusable Composer packages.
| Lifecycle Method | Allowed Operations | Strict Rule / Restriction |
|---|---|---|
register(): void |
ONLY bind things into the Service Container ($this->app->bind, $this->app->singleton) |
NEVER register event listeners, routes, or invoke other services here, because other providers have not finished registering yet! |
boot(): void |
Register View Composers, custom Blade directives, event listeners, model observers, macro definitions, and routes | Called AFTER all other service providers have finished their register() method, ensuring all services are bound and ready. |
Generate a dedicated service provider for an external Analytics SDK:
php artisan make:provider AnalyticsServiceProvider
Open app/Providers/AnalyticsServiceProvider.php:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\AnalyticsClient;
use Illuminate\Support\Facades\Blade;
class AnalyticsServiceProvider extends ServiceProvider
{
public function register(): void
{
// Bind singleton analytics client
$this->app->singleton(AnalyticsClient::class, function ($app) {
return new AnalyticsClient(
trackingId: config('services.analytics.tracking_id')
);
});
}
public function boot(): void
{
// Register custom Blade directive in boot()
Blade::directive('trackPageView', function () {
return "<?php app(App\Services\AnalyticsClient::class)->track(); ?>";
});
}
}
If you want to distribute a reusable feature to the open-source community via Composer, configure Package Discovery in your package's composer.json:
"extra": {
"laravel": {
"providers": [
"Veewom\\Billing\\BillingServiceProvider"
],
"aliases": {
"Billing": "Veewom\\Billing\\Facades\\Billing"
}
}
}
When a developer executes composer require veewom/billing, Laravel automatically discovers and registers your provider without requiring any manual configuration in their code!
Broaden your backend architecture, REST API design, and enterprise production engineering expertise:
Master the container mechanics before building custom service providers.
Register application events, listeners, and observers in provider boot methods.
Register scheduled commands and package routes within service providers.
Explain the difference between register() and boot() lifecycle methods in viva.