Skip to content

Configuration

Getting Started

Configuration

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 change it in a Configure function of your own. Laravel gives your code its settings as a typed config.Config struct, so a misspelled setting fails to compile instead of quietly reading an empty value.

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 the .env file in your application's root directory. A new 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. When your application starts, Laravel also copies the .env file's variables into the process's environment, so a library that calls os.Getenv, such as a payment provider's SDK, sees them too.

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"
3DATABASE_URL='postgres://app:[email protected]/app'
1APP_NAME="My Application"
2MAIL_FROM_NAME="${APP_NAME} Support"
3DATABASE_URL='postgres://app:[email protected]/app'

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_URL and 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 your code has a context, such as in a handler. The config package has constants for local, testing, staging, and production:

1env := config.From(r).App.Env
2 
3if env == config.Local {
4 // The environment is local...
5}
6 
7if env == config.Local || env == config.Staging {
8 // The environment is either local or staging...
9}
1env := config.From(r).App.Env
2 
3if env == config.Local {
4 // The environment is local...
5}
6 
7if env == config.Local || env == config.Staging {
8 // The environment is either local or staging...
9}

The built-in settings

Each part of the framework has a section of config.Config, and each of its fields reads an environment variable. These are the settings most applications change:

Field Variable Default What it sets
App.Name APP_NAME Laravel Your application's name.
App.Env APP_ENV production The environment your application runs in.
App.Debug APP_DEBUG false Whether error pages show details.
App.URL APP_URL http://localhost The URL your application is served at.
App.Key APP_KEY none The encryption key.
Server.Host SERVER_HOST 127.0.0.1 The address the server listens on.
Server.Port SERVER_PORT 8000 The port the server listens on.
Database.URL DATABASE_URL none The database to connect to.
Database.WriteURL DB_WRITE_URL DATABASE_URL The database that writes and transactions use when the connection has read replicas.
Database.ReadHosts DB_READ_HOSTS none The read replicas, as hosts or full URLs separated by commas.
Database.Sticky DB_STICKY false Whether reads after a write use the primary for the rest of the request.
Session.Driver SESSION_DRIVER cookie Where session data is kept.
Session.Lifetime SESSION_LIFETIME 120 minutes How long an idle session lasts.
Cache.Store CACHE_STORE memory Where the cache keeps its values.
Cache.Connection DB_CACHE_CONNECTION The default database The database cache store's connection, one of cfg.Database.Connections.
Cache.LockConnection DB_CACHE_LOCK_CONNECTION Cache.Connection The connection for the database cache store's locks.
Filesystems.Default FILESYSTEM_DISK local The default storage disk.
Log.Level LOG_LEVEL info The lowest log level that Laravel writes.
Log.Channels LOG_CHANNEL stderr Where Laravel writes log lines: stderr, stdout, daily, or a comma-separated list of them.
Mail.Mailer MAIL_MAILER log The mailer that sends your email.
Queue.Default QUEUE_CONNECTION database when DATABASE_URL is set, otherwise sync The connection that Laravel pushes jobs to.
Redis.Connections["default"] REDIS_URL redis://127.0.0.1:6379 The Redis connection that your code, sessions, and queues use.
Inertia.SSR INERTIA_SSR false Whether Inertia pages render on the server first.

The config package's documentation lists every field with the variable it reads, and each feature's guide covers its own settings.

Changing Laravel's configuration

Environment variables cover most settings, but some need code, such as a second database connection or a storage disk of your own. For those, give your options a Configure function in bootstrap/app.go. Laravel calls the function with the configuration it built from your environment, and the function changes only the fields it needs.

For example, to add a second database connection for a reporting database, add the connection to cfg.Database.Connections:

1// bootstrap/app.go
2package bootstrap
3 
4import (
5 laravel "go.laravel.com"
6 "go.laravel.com/config"
7)
8 
9func Options() laravel.Options {
10 return laravel.Options{
11 Configure: configure,
12 // ...
13 }
14}
15 
16func configure(cfg *config.Config, env *config.Env) {
17 cfg.Database.Connections = map[string]config.Connection{
18 "reporting": {URL: env.String("REPORTING_DATABASE_URL", "")},
19 }
20}
1// bootstrap/app.go
2package bootstrap
3 
4import (
5 laravel "go.laravel.com"
6 "go.laravel.com/config"
7)
8 
9func Options() laravel.Options {
10 return laravel.Options{
11 Configure: configure,
12 // ...
13 }
14}
15 
16func configure(cfg *config.Config, env *config.Env) {
17 cfg.Database.Connections = map[string]config.Connection{
18 "reporting": {URL: env.String("REPORTING_DATABASE_URL", "")},
19 }
20}

By the time configure runs, cfg already holds your default connection from DATABASE_URL, along with every other setting your environment sets. The database guide covers connections in detail.

Laravel runs configure in your tests too, on the test configuration, so your tests have the same connections and disks as your application.

Reading environment variables

The configure function reads variables through its env argument. The String, Int, and Bool methods return the fallback you give them when the variable isn't set, or when it's empty, such as REPORTING_DATABASE_URL=. List splits a comma-separated value into a slice of strings:

1lifetime := env.Int("SESSION_LIFETIME", 120)
2domain := env.String("SESSION_DOMAIN", "")
3key := env.Require("STRIPE_KEY")
4roles := env.List("ADMIN_ROLES") // ADMIN_ROLES=admin,editor gives ["admin", "editor"]
1lifetime := env.Int("SESSION_LIFETIME", 120)
2domain := env.String("SESSION_DOMAIN", "")
3key := env.Require("STRIPE_KEY")
4roles := env.List("ADMIN_ROLES") // ADMIN_ROLES=admin,editor gives ["admin", "editor"]

Use Require for a variable your application can't start without; if it isn't set, Laravel reports it alongside any other invalid variables at startup.

For a setting with a type of its own, such as a length of time, env.Value takes a function that parses the variable's text:

1timeout := env.Value("REPORTING_TIMEOUT", 10*time.Second, time.ParseDuration)
1timeout := env.Value("REPORTING_TIMEOUT", 10*time.Second, time.ParseDuration)

When a variable has a value that doesn't make sense, such as APP_DEBUG=maybe, your application refuses to start and lists every problem, including those in the variables your own code reads:

1config: APP_DEBUG is set to "maybe", which isn't true or false
2config: SERVER_PORT is set to "http", which isn't a port from 1 to 65535
1config: APP_DEBUG is set to "maybe", which isn't true or false
2config: SERVER_PORT is set to "http", which isn't a port from 1 to 65535

Accessing configuration values

You may read your configuration anywhere in your application, such as in a handler, middleware, a job, or a command, by calling config.From with the context your code receives. Each part of the framework has its own section, such as App, Session, or Mail, and each setting is a field on it. In a handler, pass the request:

1package welcome
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/web"
6)
7 
8func Show(r *web.Request) *web.Response {
9 return web.Text("Welcome to " + config.From(r).App.Name)
10}
1package welcome
2 
3import (
4 "go.laravel.com/config"
5 "go.laravel.com/web"
6)
7 
8func Show(r *web.Request) *web.Response {
9 return web.Text("Welcome to " + config.From(r).App.Name)
10}

Settings you add for your own application, such as your Stripe key, live on your application's services instead, as your own settings describes.

The functions that register your routes and customize your middleware are the exception. They run while Laravel builds your application, before any request arrives, so they have no context to pass to config.From. Instead, they receive the configuration as their second argument. The configuration is complete by then, so a routes function may use it to decide what to register, such as a route you only want on your machine:

1// routes/web.go
2func Web(route *routing.Router, cfg *config.Config) {
3 route.Get("/", welcome.Show)
4 
5 if cfg.App.Env == config.Local {
6 route.Get("/mail-preview", mailpreview.Show)
7 }
8}
1// routes/web.go
2func Web(route *routing.Router, cfg *config.Config) {
3 route.Get("/", welcome.Show)
4 
5 if cfg.App.Env == config.Local {
6 route.Get("/mail-preview", mailpreview.Show)
7 }
8}

Every request shares the same config.Config, so treat it as read-only once your application is built. A handler that changed a field would change the setting for every other request too.

Your own settings

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. Read those settings from the same environment Laravel reads, so they come from .env on your machine and from the process's environment on your servers.

Laravel passes that environment to services.New, the function in services/services.go that builds your application's services. Read each setting where you build the service that uses it. For a few settings without a dedicated client, you may define a small struct directly in services/services.go, add a field to Services, and set it from the environment:

1// services/services.go
2package services
3 
4import (
5 "context"
6 "time"
7 
8 laravel "go.laravel.com"
9 "go.laravel.com/config"
10)
11 
12type Services struct {
13 Stripe Stripe
14}
15 
16type Stripe struct {
17 // Key is Stripe's secret key.
18 Key string
19 // Timeout is how long to wait for Stripe before giving up.
20 Timeout time.Duration
21}
22 
23func New(env *config.Env, app *laravel.App) Services {
24 return Services{
25 Stripe: Stripe{
26 Key: env.String("STRIPE_KEY", ""),
27 Timeout: time.Duration(env.Int("STRIPE_TIMEOUT", 10)) * time.Second,
28 },
29 }
30}
31 
32func From(ctx context.Context) *Services {
33 return laravel.ServicesOf[*Services](ctx)
34}
1// services/services.go
2package services
3 
4import (
5 "context"
6 "time"
7 
8 laravel "go.laravel.com"
9 "go.laravel.com/config"
10)
11 
12type Services struct {
13 Stripe Stripe
14}
15 
16type Stripe struct {
17 // Key is Stripe's secret key.
18 Key string
19 // Timeout is how long to wait for Stripe before giving up.
20 Timeout time.Duration
21}
22 
23func New(env *config.Env, app *laravel.App) Services {
24 return Services{
25 Stripe: Stripe{
26 Key: env.String("STRIPE_KEY", ""),
27 Timeout: time.Duration(env.Int("STRIPE_TIMEOUT", 10)) * time.Second,
28 },
29 }
30}
31 
32func From(ctx context.Context) *Services {
33 return laravel.ServicesOf[*Services](ctx)
34}

New applications already have the From function, which returns your services from a context. The env argument has the same methods as configure's. If a variable holds a value they can't read, such as STRIPE_TIMEOUT=soon, your application refuses to start and lists the problem. Once an integration grows into a full client of its own, move it to its own package and wire it in services.New, as the services guide's section on organizing services as your application grows describes.

The Timeout field shows how to read a length of time. Environment variables hold plain text, so time.Second says that STRIPE_TIMEOUT=30 means 30 seconds. Without the variable, the timeout is 10 seconds. The field always holds a time.Duration that you may pass straight to the HTTP client, as the handler below does.

To use your settings in a handler, pass the request to services.From:

1package payments
2 
3import (
4 "net/url"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8 
9 "app/services"
10)
11 
12func Store(r *web.Request) *web.Response {
13 stripe := services.From(r).Stripe
14 
15 _, err := httpclient.Token(stripe.Key).
16 Timeout(stripe.Timeout).
17 Form(url.Values{"amount": {"2000"}, "currency": {"usd"}}).
18 Post(r, "https://api.stripe.com/v1/payment_intents")
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 return web.Back()
24}
1package payments
2 
3import (
4 "net/url"
5 
6 "go.laravel.com/httpclient"
7 "go.laravel.com/web"
8 
9 "app/services"
10)
11 
12func Store(r *web.Request) *web.Response {
13 stripe := services.From(r).Stripe
14 
15 _, err := httpclient.Token(stripe.Key).
16 Timeout(stripe.Timeout).
17 Form(url.Values{"amount": {"2000"}, "currency": {"usd"}}).
18 Post(r, "https://api.stripe.com/v1/payment_intents")
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 return web.Back()
24}

Elsewhere, such as in a job or a command, pass the ctx your code receives:

1key := services.From(ctx).Stripe.Key
1key := services.From(ctx).Stripe.Key

Give a secret such as STRIPE_KEY an empty fallback, and have the code that uses it return an error naming the variable when it's empty. Don't make services.New fail when a secret is missing: Laravel builds your services for every command, so on a fresh clone with no .env file yet, key:generate would fail before it could create one.

Debug mode

APP_DEBUG controls how much the user sees when something goes wrong. With debug mode on, a server error's error page shows the error's message and type, and a panic's stack. With debug mode off, the page says only "Server Error". 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 and storage directories. To build a path to a file in one of them, use the App section's StoragePath and PublicPath methods, which join their arguments onto the directory:

1app := config.From(ctx).App
2 
3invoice := app.StoragePath("app", "invoices", "1234.pdf")
4logo := app.PublicPath("images", "logo.svg")
1app := config.From(ctx).App
2 
3invoice := app.StoragePath("app", "invoices", "1234.pdf")
4logo := app.PublicPath("images", "logo.svg")

Laravel looks for these directories in your application's base path, and resolves the relative paths you give to web.File and web.Download against it too. While you develop, the base path is the directory that holds your go.mod file, whichever directory you run laravel or go test from. A deployed binary has no go.mod file beside it, so its base path is the directory you start it from.

If a process manager starts your binary from somewhere else, set APP_BASE_PATH to the directory that holds public and storage:

1APP_BASE_PATH=/var/www/app
1APP_BASE_PATH=/var/www/app

You may set APP_BASE_PATH in your server's environment or in your .env file. Laravel still reads .env from the directory that holds go.mod, or from the directory you start a deployed binary in, rather than from the base path.

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 tests/tests.go. The testing guide lists the overrides new applications start with.

To change a variable for one test, pass laraveltest.Env to tests.New. It applies to both Laravel's settings and your own settings. For example, this test checks that the welcome page shows the application's name:

1package feature_test
2 
3import (
4 "testing"
5 
6 "go.laravel.com/laraveltest"
7 
8 "app/tests"
9)
10 
11func TestTheWelcomePageShowsTheApplicationName(t *testing.T) {
12 client := tests.New(t, laraveltest.Env(map[string]string{
13 "APP_NAME": "Bookings",
14 }))
15 
16 client.Get("/").AssertOK().AssertProp("name", "Bookings")
17}
1package feature_test
2 
3import (
4 "testing"
5 
6 "go.laravel.com/laraveltest"
7 
8 "app/tests"
9)
10 
11func TestTheWelcomePageShowsTheApplicationName(t *testing.T) {
12 client := tests.New(t, laraveltest.Env(map[string]string{
13 "APP_NAME": "Bookings",
14 }))
15 
16 client.Get("/").AssertOK().AssertProp("name", "Bookings")
17}

laraveltest.Env changes only the variables you name. Every other setting keeps its value from .env and tests/tests.go.