Laravel - .env vs database.php

.env is short for environment and thus that is your environment configurations.

The database.php configuration contains non-critical information.

You obviously won't have your database's username's password in your source control or available in the code.

In order to keep everything safe or to keep information saved that is environment-defined... you keep them in .env file

Laravel will prioritize .env variables.


A little more detailed answer:

The config Files are where you store all configurations. You shouldn't add any username, passwords or other secret informations in them, because they will be in your source control.

All secret informations and all environment dependant informations should be stored in your .env file. With this you can have different configuration values in local/testing/production with just a different .env file.

In your config files you access the information in you .env files, if necessary.

When use what from another answer

  • use env() only in config files
  • use App::environment() for checking the environment (APP_ENV in .env).
  • use config('app.var') for all other env variables, ex. config('app.debug')
  • create own config files for your own ENV variables. Example:
    In your .env:

    MY_VALUE=foo

example config app/myconfig.php

return [
    'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];

Access in your code:

config('myconfig.myvalue') // will result in 'foo'


In your ".env" file you have your settings. in the ".php" files like your "database.php" file this is the default value for the property and normally, the corresponding value in the ".env" file is use here with this syntax : 'database' => env('database', 'default_value'),

Tags:

Laravel