DEV Community

Cover image for Laravel Configurations
Samuel K.M
Samuel K.M

Posted on • Updated on

Laravel Configurations

All of the configuration files for the Laravel framework are stored in the config directory. Each option is documented.

It is often helpful to have different configuration values based on the environment where the application is running. For example, you may wish to use a different cache driver locally than you do on your production server.

To make this a cinch, Laravel utilizes the DotEnv PHP library. ** In a fresh Laravel installation, the root directory of your application will contain a **.env.example file that defines many common environment variables. During the Laravel installation process, this file will automatically be copied to .env.

All of the variables listed in this file will be loaded into the $_ENV PHP super-global when your application receives a request. However, you may use the env helper to retrieve values from these variables in your configuration files.Here is a sample of the env file (Take note of how the env variable are retrieved in the config file using env() helper function):

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:aL/O2tKpBXjl1Vdc2EUj/3jzPF5E5/5/4XJjNY0cLB0=
APP_DEBUG=true
APP_URL=http://laravel-refresher-app.test

LOG_CHANNEL=stack
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel_refresher_app
DB_USERNAME=sail
DB_PASSWORD=password

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=memcached

REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://meilisearch:7700

Enter fullscreen mode Exit fullscreen mode

These values are then retrieved from various Laravel configuration files within the config directory using Laravel's env function.

Here is an example of the broadcasting config file

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "ably", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'useTLS' => true,
            ],
        ],

        'ably' => [
            'driver' => 'ably',
            'key' => env('ABLY_KEY'),
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

Enter fullscreen mode Exit fullscreen mode

**Environment File Security
**NB
Your .env file should not be committed to your application's source control, since each developer / server using your application could require a different environment configuration. Furthermore, this would be a security risk in the event an intruder gains access to your source control repository, since any sensitive credentials would get exposed.

NB:If you need to define an environment variable with a value that contains spaces, you may do so by enclosing the value in double quotes:

APP_NAME="My Application"
Enter fullscreen mode Exit fullscreen mode

**** Determining The Current Environment

The current application environment is determined via the APP_ENV variable from your .env file. You may access this value via the environment method on the App facade(checkout my Laravel Facade Tutorial):

use Illuminate\Support\Facades\App;
$environment = App::environment();
Enter fullscreen mode Exit fullscreen mode

You may also pass arguments to the environment method to determine if the environment matches a given value. The method will return true if the environment matches any of the given values:

if (App::environment('local')) {
    // The environment is local
}

if (App::environment(['local', 'staging'])) {
    // The environment is either local OR staging...
}
Enter fullscreen mode Exit fullscreen mode

Accessing Configuration Values

You may easily access your configuration values using the global config helper function from anywhere in your application. The configuration values may be accessed using "dot" syntax, which includes:

  • the name of the file
  • and option you wish to access.

A default value may also be specified and will be returned if the configuration option does not exist:

$value = config('app.timezone');
// Retrieve a default value if the configuration value does not exist...
$value = config('app.timezone', 'Asia/Seoul');
Enter fullscreen mode Exit fullscreen mode

To set configuration values at runtime, pass an array to the config helper:

config(['app.timezone' => 'America/Chicago']);
Enter fullscreen mode Exit fullscreen mode

Configuration Caching

To give your application a speed boost, you should cache all of your configuration files into a single file using

php artisan config:cache
Enter fullscreen mode Exit fullscreen mode

This will combine all of the configuration options for your application into a single file which can be quickly loaded by the framework.

You should typically run the php artisan config:cache command as part of your production deployment process.

NB The command should not be run during local development as configuration options will frequently need to be changed during the course of your application's development.

Once the configuration has been cached, the .env file will not be loaded; therefore, the env function will only return external, system level environment variables.

Debug Mode

The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false.
NB If the variable is set to true in production, you risk exposing sensitive configuration values to your application's end users.

Maintenance Mode

When your application is in maintenance mode, a custom view will be displayed for all requests into your application. This makes it easy to "disable" your application while it is updating or when you are performing maintenance. A maintenance mode check is included in the default middleware stack for your application.

If the application is in maintenance mode, a Symfony\Component\HttpKernel\Exception\HttpException instance will be thrown with a status code of 503.

To enable maintenance mode, execute the down Artisan command:

php artisan down
Enter fullscreen mode Exit fullscreen mode

If you would like the Refresh HTTP header to be sent with all maintenance mode responses, you may provide the refresh option when invoking the down command. The Refresh header will instruct the browser to automatically refresh the page after the specified number of seconds:

php artisan down --refresh=15
Enter fullscreen mode Exit fullscreen mode

You may also provide a retry option to the down command, which will be set as the Retry-After HTTP header's value, although browsers generally ignore this header:

php artisan down --retry=60
Enter fullscreen mode Exit fullscreen mode

Bypassing Maintenance Mode

Even while in maintenance mode, you may use the secret option to specify a maintenance mode bypass token:

php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515"
After placing the application in maintenance mode, you may navigate to the application URL matching this token and Laravel will issue a maintenance mode bypass cookie to your browser:

https://example.com/1630542a-246b-4b66-afa1-dd72a4c43515

When accessing this hidden route, you will then be redirected to the / route of the application. Once the cookie has been issued to your browser, you will be able to browse the application normally as if it was not in maintenance mode.

Pre-Rendering The Maintenance Mode View

If you utilize the php artisan down command during deployment, your users may still occasionally encounter errors if they access the application while your Composer dependencies or other infrastructure components are updating. This occurs because a significant part of the Laravel framework must boot in order to determine your application is in maintenance mode and render the maintenance mode view using the templating engine.

For this reason, Laravel allows you to pre-render a maintenance mode view that will be returned at the very beginning of the request cycle. This view is rendered before any of your application's dependencies have loaded. You may pre-render a template of your choice using the down command's render option:

php artisan down --render="errors::503"
Enter fullscreen mode Exit fullscreen mode

Redirecting Maintenance Mode Requests
While in maintenance mode, Laravel will display the maintenance mode view for all application URLs the user attempts to access. If you wish, you may instruct Laravel to redirect all requests to a specific URL. This may be accomplished using the redirect option. For example, you may wish to redirect all requests to the / URI:

php artisan down --redirect=/
Disabling Maintenance Mode
To disable maintenance mode, use the up command:

php artisan up

NB: You may customize the default maintenance mode template by defining your own template atresources/views/errors/503.blade.php.

Maintenance Mode & Queues

While your application is in maintenance mode, no queued jobs will be handled. The jobs will continue to be handled as normal once the application is out of maintenance mode.

Alternatives To Maintenance Mode

Since maintenance mode requires your application to have several seconds of downtime, consider alternatives like Laravel Vapor and Envoyer to accomplish zero-downtime deployment with Laravel.

Oldest comments (0)