Configuration
- Introduction
- Environment configuration
- Changing Laravel's configuration
- Your own settings
- 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 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:
APP_NAME="My Application"
MAIL_FROM_NAME="${APP_NAME} Support"
DATABASE_URL='postgres://app:s3cr$t@127.0.0.1/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_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 your code has a context, such as in a handler. The config package has constants for local, testing, staging, and production:
env := config.From(r).App.Env
if env == config.Local {
// The environment is local...
}
if env == config.Local || env == config.Staging {
// The environment is either local or staging...
}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:
// bootstrap/app.go
package bootstrap
import (
laravel "go.laravel.com"
"go.laravel.com/config"
)
func Options() laravel.Options {
return laravel.Options{
Configure: configure,
// ...
}
}
func configure(cfg *config.Config, env *config.Env) {
cfg.Database.Connections = map[string]config.Connection{
"reporting": {URL: env.String("REPORTING_DATABASE_URL", "")},
}
}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:
lifetime := env.Int("SESSION_LIFETIME", 120)
domain := env.String("SESSION_DOMAIN", "")
key := env.Require("STRIPE_KEY")
roles := 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:
timeout := 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:
config: APP_DEBUG is set to "maybe", which isn't true or false
config: SERVER_PORT is set to "http", which isn't a port from 1 to 65535Accessing 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:
package welcome
import (
"go.laravel.com/config"
"go.laravel.com/web"
)
func Show(r *web.Request) *web.Response {
return web.Text("Welcome to " + config.From(r).App.Name)
}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:
// routes/web.go
func Web(route *routing.Router, cfg *config.Config) {
route.Get("/", welcome.Show)
if cfg.App.Env == config.Local {
route.Get("/mail-preview", mailpreview.Show)
}
}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:
// services/services.go
package services
import (
"context"
"time"
laravel "go.laravel.com"
"go.laravel.com/config"
)
type Services struct {
Stripe Stripe
}
type Stripe struct {
// Key is Stripe's secret key.
Key string
// Timeout is how long to wait for Stripe before giving up.
Timeout time.Duration
}
func New(env *config.Env, app *laravel.App) Services {
return Services{
Stripe: Stripe{
Key: env.String("STRIPE_KEY", ""),
Timeout: time.Duration(env.Int("STRIPE_TIMEOUT", 10)) * time.Second,
},
}
}
func From(ctx context.Context) *Services {
return laravel.ServicesOf[*Services](ctx)
}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:
package payments
import (
"net/url"
"go.laravel.com/httpclient"
"go.laravel.com/web"
"app/services"
)
func Store(r *web.Request) *web.Response {
stripe := services.From(r).Stripe
_, err := httpclient.Token(stripe.Key).
Timeout(stripe.Timeout).
Form(url.Values{"amount": {"2000"}, "currency": {"usd"}}).
Post(r, "https://api.stripe.com/v1/payment_intents")
if err != nil {
return web.Fail(err)
}
return web.Back()
}Elsewhere, such as in a job or a command, pass the ctx your code receives:
key := 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:
app := config.From(ctx).App
invoice := app.StoragePath("app", "invoices", "1234.pdf")
logo := 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:
APP_BASE_PATH=/var/www/appYou 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:
package feature_test
import (
"testing"
"go.laravel.com/laraveltest"
"app/tests"
)
func TestTheWelcomePageShowsTheApplicationName(t *testing.T) {
client := tests.New(t, laraveltest.Env(map[string]string{
"APP_NAME": "Bookings",
}))
client.Get("/").AssertOK().AssertProp("name", "Bookings")
}laraveltest.Env changes only the variables you name. Every other setting keeps its value from .env and tests/tests.go.