Laravel - Configuration

Laravel - Configuration

Laravel Configuration Guide

In the previous chapter, we explored Laravel's core configuration files located in the config directory. This chapter provides a detailed overview of the types of configurations and best practices for working with them.

Environment Configuration

Laravel uses environment variables to manage services and settings for your web application. These are defined in the .env file located in the root directory of your project. This file contains values required to initialize your application's configuration.

Example .env File:

APP_ENV=local APP_DEBUG=true APP_KEY=base64:ZPt2wmKE/X4eEhrzJU6XX4R93rCwYG8E2f8QUA7kGK8= APP_URL=http://localhost DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=name_db DB_USERNAME=username_db DB_PASSWORD=secret CACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=sync REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER=smtp MAIL_HOST=mailtrap.io MAIL_PORT=2525 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

Important Notes:

  • Do not commit the .env file to version control, as it contains sensitive and environment-specific information.

  • Instead, include a .env.example file with default values for reference and onboarding new developers.

Accessing Environment Variables

Environment variables can be accessed using Laravel’s env() helper function. These variables are also available in the global $_ENV array when the application processes a request.

Example:

'env' => env('APP_ENV', 'production'),

This example fetches the APP_ENV variable, defaulting to 'production' if it's not set.

Accessing Configuration Values

To retrieve or set configuration values within your application, use the global config() helper.

Example: Setting Timezone

config(['app.timezone' => 'Asia/Bakong']);

If a value is not already set, the helper returns the default specified value.

Configuration Caching

To optimize performance, Laravel allows you to cache all configuration values into a single file. This significantly reduces load times.

Cache Configuration Command:

php artisan config:cache

This command compiles all config files into one cached file for faster loading.

Maintenance Mode

When performing updates or making configuration changes, it’s a good practice to put your application into maintenance mode.

Enable Maintenance Mode:

php artisan down

While in maintenance mode, Laravel throws a MaintenanceModeException with a 503 HTTP status code.

Disable Maintenance Mode:

php artisan up

Once you're done, your application will return to normal operation.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close