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
:
- Add it to
extra.laravel.dont-discover
incomposer.json
:
composer.json Configuration - 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:
- Add to
dont-discover
as above. - Create a dedicated service class:
class ImageService {
public function __construct() {
$this->app->register(\Intervention\Image\ImageServiceProvider::class);
}
}
Key Implementation Notes
- Dependency Handling: If a provider has dependencies:
- Register dependencies in
AppServiceProvider::register()
- Boot in
AppServiceProvider::boot()
- Register dependencies in
- 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.