Skip to content

Environment config

Table of Contents

  1. How to use
  2. Cached config
  3. ENV variables

It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use different database details for your local environment than you do on the production server.

To make this a cinch, Laravel utilizes the DotEnv PHP library which looks for environment settings in the /.env file. This file is unique for each of our servers and ignored by git.

How to use

Laravel provides an env() method to get environment variables, but its usage is pretty limited. In addition to its limited capabilities, the .env file will not be loaded once the configuration is cached, which means calling env() will only return external, system level environment variables. For these reasons, usage of this method is only allowed within config files (files present at src/config/ directory). In order to use environment variables in other scripts or classes, you have to add another variable to any config file and then use the config() method.

Example of .env file:

bash
APP_URL=true

/config/app.php

php
return [
    'url' => env('APP_URL'),
 ]

using it in Blade code:

php
@if(config('app.url'))
    {{ config('app.url') }}
@endif

Cached config

There is an ability to combine all of the configuration options (including .env file variables) for an application into a single file (by default it’s src/bootstrap/cache/config.php) which will be loaded quickly by the framework. It’s useful for production environments but a bit annoying for develop/local (because of frequently changing of configs during development).

To generate a fresh configuration cache and apply new settings on production environments, you can run the command:

php artisan config:cache

This will remove old configuration cache and create a new one.

To remove cached config file and use non-compiled config files use this command:

php artisan config:clear

ENV variables

APP_DEBUG, boolean. It defines the level of PHP errors displayed. For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application’s end users.