Configure local env providers and aliases in Laravel 5

Submitted by ivanhoe011 - 11 months ago

This code allows you to register additional package providers and aliases for different environments, similar to how it used to work in L4. While the most of local configuration in L5 can be done by .env files, you can't really separate dev packages that way. If you install a package with `composer require --dev` it will not be available in the production and if you forget to remove the providers from the app.php it will break everything. With this code you can have local/app.php config with package providers and aliases that will be merged with the main config, but only if you are in local env. It will also support using separate config for production/app.php or test/app.php (or any other environment name you use).

<?php

// Edit your app/Providers/AppServiceProvider like this

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $path = $this->app->environment() .'.app';
        $config = $this->app->make('config');
        $aliasLoader = AliasLoader::getInstance();

        if ($config->has($path)) {
            array_map([$this->app, 'register'], $config->get($path .'.providers'));

            foreach ($config->get($path .'.aliases') as $key => $class) {
                $aliasLoader->alias($key, $class);
            }
        }
    }
}

// and then you can add config/local/app.php. For example to add Debugbar only in local env:
/*
return [
    'providers' => [
            Barryvdh\Debugbar\ServiceProvider::class,
    ],
    'aliases' => [
        'Debugbar' => Barryvdh\Debugbar\Facade::class,
    ],
];

*/

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks