Featured image of post Speed Up Your Framework: How to Reduce Service Provider Boot Time

Speed Up Your Framework: How to Reduce Service Provider Boot Time

Many service providers in Laravel boot automatically, which can bloat the framework. Learn how to optimize unnecessary service providers.

Laravel has a powerful feature called service providers that makes it easy to access various services. However, this convenience comes at the cost of framework bloat. Here’s how to optimize unnecessary service providers.

Step 1: Identify Unnecessary Service Providers

Run php artisan package:discover or composer dump-auto to see all auto-loaded service providers:

Step 2: Conditionally Load Providers

Example 1: Admin Panel Optimization

The encore/laravel-admin package (a backend panel) boots on every request. Instead, load it only when the URL contains admin:

  1. Add it to extra.laravel.dont-discover in composer.json:
  2. Manually register it conditionally in AppServiceProvider:
if (str_contains(request()->getRequestUri(), 'admin')) {  
    $this->app->register(\Encore\Admin\AdminServiceProvider::class);  
}  

Example 2: Image Processing Optimization

For intervention/image (used for image manipulation), defer loading until needed:

  1. Add to dont-discover as above.
  2. Create a dedicated service class:
class ImageService {  
    public function __construct() {  
        $this->app->register(\Intervention\Image\ImageServiceProvider::class);  
    }  
}  

Key Implementation Notes

  1. Dependency Handling: If a provider has dependencies:
    • Register dependencies in AppServiceProvider::register()
    • Boot in AppServiceProvider::boot()
  2. Use Laravel’s built-in Application::register() method to handle registration and booting automatically.

Final Code Implementation


With these optimizations, you gain fine-grained control over external service providers while maintaining framework performance.