Configuration
- Introduction
- Environment configuration
- Configuration files
- Your own configuration sections
- Debug mode
- The base path
- Configuration in tests
Introduction
Your application needs settings that differ between your machine and your servers, such as your database credentials, your mail server, and the keys for the services you call. Laravel reads most of these settings from environment variables, so you rarely need to write any configuration code.
When a setting needs more than a variable, such as a second database connection, you update one of the configuration files in src/config/, or add one of your own. Every setting is a typed field, so a misspelled setting is a compile error instead of a silent mistake.
Environment configuration
It's often helpful to have different settings depending on where your application runs. For example, you may use the memory cache on your machine and Redis in production.
Laravel reads your environment variables from your application's .env file. A fresh application includes a .env.example file with the most common variables, and the installer copies it to .env for you. If you work with a team, keep .env.example up to date with placeholder values, so everyone can see which variables the application needs.
Variables set by your server or process manager take precedence over .env, so in production you may set them there instead.
Your .env file holds secrets such as your encryption key and database password, so don't commit it to source control.
Wrap a value that contains spaces in double quotes. A value may refer to another variable as ${NAME}. If a value contains a $, such as a password, place it in single quotes to keep it as written:
1APP_NAME="My Application"2MAIL_FROM_NAME="${APP_NAME} Support"1APP_NAME="My Application"2MAIL_FROM_NAME="${APP_NAME} Support"
Determining the current environment
The APP_ENV variable names the environment your application runs in. Set it to local on your machine and production on your servers. When APP_ENV isn't set, your application runs as production.
Laravel is more careful in production. For example:
- Commands that can destroy data, such as
migrate, ask you to confirm before they run. - Laravel only answers requests for the host in your
APP_URLand its subdomains.
You may also run scheduled tasks only in certain environments. Your tests always run in the testing environment.
You may check the environment anywhere in your application, such as in a handler:
1use laravel::config::app::Environment;23let environment = &laravel::config().app.env;45if environment.is_local() {6 // The environment is local...7}89if matches!(environment, Environment::Local | Environment::Staging) {10 // The environment is either local or staging...11}1use laravel::config::app::Environment;23let environment = &laravel::config().app.env;45if environment.is_local() {6 // The environment is local...7}89if matches!(environment, Environment::Local | Environment::Staging) {10 // The environment is either local or staging...11}
Configuration files
Environment variables cover most settings, but some need code, such as an extra cache store or a second database connection. For those, write a configuration file in src/config/. Your application already includes configuration files for the database and CORS, so you may edit those too.
A configuration file is a function marked #[config::section] that receives the environment and returns one of the framework's sections. For example, to add a second database connection for a reporting database in src/config/database.rs, start from Database::from_env(env) and register the extra connection:
1// src/config/database.rs2use laravel::config::database::{ConnectionConfig, Database};3use laravel::config::{self, Env};45#[config::section]6fn database(env: &Env) -> Database {7 let mut database = Database::from_env(env);89 database.add_connection(10 "reporting",11 ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default()),12 );1314 database15}1// src/config/database.rs2use laravel::config::database::{ConnectionConfig, Database};3use laravel::config::{self, Env};45#[config::section]6fn database(env: &Env) -> Database {7 let mut database = Database::from_env(env);89 database.add_connection(10 "reporting",11 ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default()),12 );1314 database15}
Database::from_env reads your default connection from DB_CONNECTION, DATABASE_URL, and DB_MAX_CONNECTIONS. The database guide covers connections in detail.
When you create a new configuration file, such as src/config/cache.rs, add a mod line for it to src/config/mod.rs:
1// src/config/mod.rs2mod cache;1// src/config/mod.rs2mod cache;
Reading environment variables
A configuration file reads variables through its Env argument. The get method converts a variable into the type you ask for, such as a number, a bool, or a Driver. It returns None when the variable isn't set, so you may follow it with a default:
1let lifetime: u64 = env.get("SESSION_LIFETIME").unwrap_or(120);2let domain: Option<String> = env.get("SESSION_DOMAIN");1let lifetime: u64 = env.get("SESSION_LIFETIME").unwrap_or(120);2let domain: Option<String> = env.get("SESSION_DOMAIN");
Read a variable your application can't run without, such as an API key, with require instead:
1let stripe_key: String = env.require("STRIPE_KEY");1let stripe_key: String = env.require("STRIPE_KEY");
When a required variable is missing, or a variable has a value that doesn't make sense, such as APP_DEBUG=maybe, your application refuses to start and lists every problem:
1the environment is invalid:2 - `APP_DEBUG` is set to `maybe`, which is invalid: provided string was not `true` or `false`3 - `STRIPE_KEY` is required, but isn't set1the environment is invalid:2 - `APP_DEBUG` is set to `maybe`, which is invalid: provided string was not `true` or `false`3 - `STRIPE_KEY` is required, but isn't set
Accessing configuration values
You may read your configuration anywhere in your application, such as in a handler, middleware, or a console command, by calling laravel::config(). Each part of the framework has its own section, such as app, session, or mail, and each setting is a field on it:
1use laravel::prelude::*;23pub async fn show() -> String {4 let config = laravel::config();56 format!("Welcome to {}", config.app.name)7}1use laravel::prelude::*;23pub async fn show() -> String {4 let config = laravel::config();56 format!("Welcome to {}", config.app.name)7}
Settings you add for your own application, such as your Stripe keys, live in sections of your own. You read those by their type, as Section<Stripe> in a handler or laravel::config().section::<Stripe>() elsewhere. The framework's sections work this way too, so Section<App> gives a handler the app section.
Service providers, which packages use to plug into your application, are the exception. They run while your application is starting up, before laravel::config() is available, so they read configuration from the app they receive instead. The configuration is complete by then, so a provider may use it to decide what to register, such as a route you only want on your machine:
1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34pub struct MailPreviewServiceProvider;56impl ServiceProvider for MailPreviewServiceProvider {7 fn register(&self, app: &mut Registrar) {8 if app.config().app.env.is_local() {9 app.routing().web(|route| {10 route.get("/mail-preview", mail_preview::show);11 });12 }13 }14}1use laravel::container::Registrar;2use laravel::foundation::ServiceProvider;34pub struct MailPreviewServiceProvider;56impl ServiceProvider for MailPreviewServiceProvider {7 fn register(&self, app: &mut Registrar) {8 if app.config().app.env.is_local() {9 app.routing().web(|route| {10 route.get("/mail-preview", mail_preview::show);11 });12 }13 }14}
Your own configuration sections
When your application calls a third-party service such as Stripe, it needs the service's key, and perhaps settings of its own, such as how long to wait for a response. Give those settings a section of your own: a struct that derives Section, with each field naming the environment variable it reads.
Your application's src/config/services.rs starts with a section for Sentry, as an example of how to define one. It's a convenient home for the credentials of the services your application calls, but you don't have to use it. To add Stripe, add a section next to Sentry's:
1// src/config/services.rs2use laravel::config::Section;3use laravel::time::ExactDuration;45#[derive(Clone, Section)]6pub struct Stripe {7 /// Stripe's secret key.8 #[env("STRIPE_KEY", required)]9 pub key: String,1011 /// The account to send payouts to, if any.12 #[env("STRIPE_ACCOUNT")]13 pub account: Option<String>,1415 /// How long to wait for Stripe before giving up.16 #[env("STRIPE_TIMEOUT", seconds, default = 10)]17 pub timeout: ExactDuration,18}1// src/config/services.rs2use laravel::config::Section;3use laravel::time::ExactDuration;45#[derive(Clone, Section)]6pub struct Stripe {7 /// Stripe's secret key.8 #[env("STRIPE_KEY", required)]9 pub key: String,1011 /// The account to send payouts to, if any.12 #[env("STRIPE_ACCOUNT")]13 pub account: Option<String>,1415 /// How long to wait for Stripe before giving up.16 #[env("STRIPE_TIMEOUT", seconds, default = 10)]17 pub timeout: ExactDuration,18}
You don't need to register the section. Laravel reads it from the environment when your application starts, and since STRIPE_KEY is required, your application won't start without it.
The timeout field shows how a section reads a length of time. Environment variables hold plain text, so seconds says that STRIPE_TIMEOUT=30 means 30 seconds. Without the variable, the timeout is 10 seconds, from default = 10. Either way, the field holds an ExactDuration that you may pass straight to the HTTP client, as the handler below does.
Each field's #[env(..)] takes the variable's name, followed by any of these options:
| Option | Means | Example |
|---|---|---|
required |
The application won't start without the variable | #[env("STRIPE_KEY", required)] |
default = .. |
The value to use when the variable isn't set | #[env("STRIPE_REGION", default = "us")] gives "us" |
seconds, minutes |
The variable is a whole number of seconds or minutes | #[env("STRIPE_TIMEOUT", seconds)] reads STRIPE_TIMEOUT=30 as 30 seconds |
separator = ", |
The variable is a list, split on the separator, for a Vec<String> field |
#[env("ADMIN_ROLES", separator = ",")] reads ADMIN_ROLES=admin,editor as ["admin", "editor"] |
To use your section in a handler, accept it as a Section argument:
1use laravel::config::Section;2use laravel::http::client;3use laravel::prelude::*;45use crate::config::services::Stripe;67pub async fn store(stripe: Section<Stripe>) -> laravel::Result<Redirect> {8 client::post("https://api.stripe.com/v1/payment_intents")9 .token(&stripe.key)10 .timeout(stripe.timeout)11 .form([("amount", "2000"), ("currency", "usd")])12 .await?;1314 Ok(Redirect::back())15}1use laravel::config::Section;2use laravel::http::client;3use laravel::prelude::*;45use crate::config::services::Stripe;67pub async fn store(stripe: Section<Stripe>) -> laravel::Result<Redirect> {8 client::post("https://api.stripe.com/v1/payment_intents")9 .token(&stripe.key)10 .timeout(stripe.timeout)11 .form([("amount", "2000"), ("currency", "usd")])12 .await?;1314 Ok(Redirect::back())15}
Elsewhere, such as in a job or a console command, read it from the configuration with section:
1let key = &laravel::config().section::<Stripe>().key;1let key = &laravel::config().section::<Stripe>().key;
Debug mode
APP_DEBUG controls how much the user sees when something goes wrong. With debug mode on, server errors render a detailed page with the error, its causes, the route, and the request. Debug mode also picks up changes to your views without a restart. Your application's .env.example turns debug mode on for local development.
Always set APP_DEBUG to false in production. Debug pages can show your users sensitive details about your application.
The base path
Your application keeps its files in the public, storage, and resources directories. To build a path to one of them, use the app section's helpers:
1let app = &laravel::config().app;23let invoice = app.storage_path("app/invoices/1234.pdf");4let logo = app.public_path("images/logo.svg");1let app = &laravel::config().app;23let invoice = app.storage_path("app/invoices/1234.pdf");4let logo = app.public_path("images/logo.svg");
Laravel looks for these directories in the directory your application starts from. If a process manager starts your application from somewhere else, set APP_BASE_PATH in the process manager's environment:
1APP_BASE_PATH=/srv/my-app1APP_BASE_PATH=/srv/my-app
Setting APP_BASE_PATH in .env doesn't work, because Laravel reads .env from the directory your application starts from. You may instead start your application from its own directory, such as with systemd's WorkingDirectory= or a container's WORKDIR.
Configuration in tests
Each test gets a configuration of its own, so changing a setting in one test never affects another. Tests read your .env file (or .env.testing when present) and apply the overrides in src/testing.rs. The testing guide lists the overrides new applications start with.
To change a variable for one test, write a function in your test file that builds the application with with_env, then name it in the test's attribute:
1use laravel::testing::prelude::*;23fn short_sessions() -> Application {4 app::testing::configure().with_env("SESSION_LIFETIME", "5").create()5}67#[laravel::test(app = short_sessions)]8async fn sessions_expire_after_five_minutes(app: Application) {9 assert_eq!(app.config().session.lifetime, 5.minutes());10}1use laravel::testing::prelude::*;23fn short_sessions() -> Application {4 app::testing::configure().with_env("SESSION_LIFETIME", "5").create()5}67#[laravel::test(app = short_sessions)]8async fn sessions_expire_after_five_minutes(app: Application) {9 assert_eq!(app.config().session.lifetime, 5.minutes());10}
with_env changes only the variable you name. Every other setting keeps its value from .env and src/testing.rs.