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:
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:
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
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:
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:
While in maintenance mode, Laravel throws a MaintenanceModeException
with a 503 HTTP status code.
Disable Maintenance Mode:
Once you're done, your application will return to normal operation.