简体   繁体   中英

Laravel 5.4 environment based config files

I am trying to change the Laravel configuration variables based on environment, but I do not know how.

Code to get config is

Config::get( 'contants.api_url' );

I am trying to have a separate results for the live environment and the development environment.

Real life scenario

I need to override some config files, so everybody who is using the development environment, has the same base configuration. I cannot use the.env file for this, because it is not shared between the team and everybody has their own version of it.

What did I try:

I read here Laravel 5 configuration - environments and overriding that you can create subfolders within your /config folder, that match the environment, to override the default config files. Alas it did not work for me and the Laravel 5.4 documentation on the subject matter ( https://laravel.com/docs/5.4/configuration#retrieving-environment-configuration ) did not speak about this option, thus I believe it might have been deprecated.

One option could be to use a service provider. If you're only going to be overriding one or two values then you might as well just use your AppServiceProvider , otherwise I would suggest creating a new service (eg ConfigServiceProvider ).

In the boot() method of your service provider you could add something like:

if (app()->environment() === 'local') {
   config()->set('contants.api_url', 'http://example.com');
}

To change the configuration variables based on environment, this will do:

Example file: config/database.php

       'mysql' => [
            'driver' => mysql,
            'url' => env('DATABASE_URL'),
            'host'=> (env('APP_ENV') === 'local' ? env('DB_HOST_LOCAL') : env('DB_HOST_PRODUCTION')),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'default'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'options' => (env('APP_ENV') === 'local' ? [
                'some_option' =>  env('SOME_ENV')
            ] : []),
        ],

Tested and works on Laravel 5.8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM