In laravel, there are times when you need to install packages only for your local or development environment for debugging and testing purposes.
Even if you specify those packages in require-dev section of your composer.json file, you still need to add the service providers and aliases in the config/app.php file. Without that, it won’t work.
With Laravel 5, you can easily load service providers based on your environment. In this example, we’ll install the barryvdh/laravel-debugbar package which displays a pretty debug information during testing of your application.
1. Add the package to your composer.json file
"require-dev": { "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.*", "phpunit/phpunit": "~4.0", "phpspec/phpspec": "~2.1", "barryvdh/laravel-debugbar": "^2.0" }
Save the file, and do a composer update.
composer update
2. Create a new ServiceProvider called LocalServiceProvider
// file: app/Providers/LocalServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class LocalServiceProvider extends ServiceProvider { protected $providers = [ 'Barryvdh\Debugbar\ServiceProvider' ]; protected $aliases = [ 'Debugbar' => 'Barryvdh\Debugbar\Facade' ]; /** * Bootstrap any application services. * * @return void */ public function boot() { // } /** * Register any application services. * * @return void */ public function register() { //register the service providers for local environment if ($this->app->isLocal() && !empty($this->providers)) { foreach ($this->providers as $provider) { $this->app->register($provider); } //register the alias if (!empty($this->aliases)) { foreach ($this->aliases as $alias => $facade) { $this->app->alias($alias, $facade); } } } } }
3. Add the new ServiceProvider to the config/app.php service provider list
/* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\LocalServiceProvider::class,
To ensure laravel detects the correct environment, you have to make sure you are specifying the correct environment in your .env file.
APP_ENV=local
Now whenever you have packages you want to use only in your local environment, you can append their service providers to the $providers array and their aliases to the $aliases array. This way, they don’t get loaded unnecessarily in your production environment.
Super!
Bugging me for days and as usual, while the solution is right in front of me all the time! A simple, clean, in other words Laravel-like solution, great work! Thanks 🙂
Worked for me (Laravel 5.1).