Feature Flags
- Introduction
- Configuration
- Defining features
- Rich values
- Checking features
- Before hooks
- Updating values
- Features by name
- Feature stores of your own
- Testing
Introduction
Feature flags let you roll out new functionality gradually, without a deploy at each step. You may turn a new API on for your staff first, expand it to one customer in a hundred, and eventually turn it on for everyone. You may also run A/B experiments, such as showing each user one of three colors for your "Buy now" button and keeping the color that sells best.
In Laravel, a feature is a Go function that decides the feature's first value for a user, a team, or the whole application. Laravel stores that value, so the user gets the same answer on every later request until you change or forget it. The feature package defines your features and checks them with the context you pass it, such as the request in a handler.
Configuration
By default, Laravel stores feature values in your database, so every server agrees on each user's value and stored values survive deploys. Configure where Laravel stores feature values with these environment variables:
| Variable | Default | Purpose |
|---|---|---|
FEATURE_STORE |
database |
database, memory, or the name of a store that a package adds. |
DB_FEATURE_CONNECTION |
The default database | The database store's connection, one of cfg.Database.Connections. |
DB_FEATURE_TABLE |
features |
The database store's table. |
The memory store keeps values in each process's memory and loses them when the process stops. It's fine for local development and tests, and Laravel uses it automatically when your application has no database, which is when DATABASE_URL isn't set.
The features table
The database store keeps values in a features table. Before you check your first feature, create a migration that calls feature.CreateTable(ctx) and list it in migrations.All:
1// database/migrations/2026_01_01_000000_create_features_table.go2package migrations34import (5 "context"67 "go.laravel.com/feature"8)910func createFeaturesTable(ctx context.Context) error {11 return feature.CreateTable(ctx)12}1// database/migrations/2026_01_01_000000_create_features_table.go2package migrations34import (5 "context"67 "go.laravel.com/feature"8)910func createFeaturesTable(ctx context.Context) error {11 return feature.CreateTable(ctx)12}
Then run your migrations:
1laravel migrate1laravel migrate
feature.CreateTable creates the features table (or the table configured by DB_FEATURE_TABLE) with its unique index on name and scope, so concurrent first-time checks agree on one stored value.
Defining features
To define a feature, call feature.Define with the feature's name and its function, and keep the result in a package-level variable in a features package. The function takes a context and the scope it decides for, usually your *models.User, and returns whether the feature is active. For example, if your User model has an IsStaff field, this feature enables a new API for staff and for one in a hundred other users:
1// features/features.go2package features34import (5 "context"67 "go.laravel.com/feature"8 "go.laravel.com/lottery"910 "app/models"11)1213var NewAPI = feature.Define("new_api", func(ctx context.Context, user *models.User) (bool, error) {14 return user.IsStaff || lottery.Odds(1, 100).Draw(ctx), nil15})1// features/features.go2package features34import (5 "context"67 "go.laravel.com/feature"8 "go.laravel.com/lottery"910 "app/models"11)1213var NewAPI = feature.Define("new_api", func(ctx context.Context, user *models.User) (bool, error) {14 return user.IsStaff || lottery.Odds(1, 100).Draw(ctx), nil15})
The function runs once for each user, on the first check of the feature for that user, and Laravel stores what it returns. Later checks read the stored value without running the function again, so each user gets one lottery draw and keeps its result.
Listing your features
Laravel needs to know every feature your application defines, so list each one in Options.Features. Laravel uses the list to check that no two features share a name, to share every feature with your pages, and to keep the listed features' values when you purge the features you removed. Keep the list in features.All, next to your features, and pass it to Options.Features in bootstrap/app.go:
1// features/features.go2var All = []feature.Definition{NewAPI, PurchaseButton, BillingV2}1// features/features.go2var All = []feature.Definition{NewAPI, PurchaseButton, BillingV2}
1// bootstrap/app.go2return laravel.Options{3 // ...4 Features: features.All,5}1// bootstrap/app.go2return laravel.Options{3 // ...4 Features: features.All,5}
Checking a feature that isn't in the list panics with a message that tells you to add it. A package adds its own features with app.Features when it registers, so you don't list a package's features yourself.
Stored names
Laravel stores each value under the name you pass to feature.Define, not under the Go variable's name. Renaming a feature would orphan every value already stored under the old name, so keep the stored name when you rename the variable:
1var NewServersAPI = feature.Define(2 "new_api",3 func(ctx context.Context, user *models.User) (bool, error) {4 return user.IsStaff, nil5 },6)1var NewServersAPI = feature.Define(2 "new_api",3 func(ctx context.Context, user *models.User) (bool, error) {4 return user.IsStaff, nil5 },6)
A name may be any text, so you may also give a feature a name that reads well in your pages or admin screens, such as purchase-button.
Queries, services, and configuration
A feature's function receives the context of the check, so it may query the database or call another service before it decides. For example, this feature enables a new editor for authors with at least ten published posts:
1// features/features.go2package features34import (5 "context"67 "go.laravel.com/feature"8 "go.laravel.com/model"910 "app/models"11)1213var NewEditor = feature.Define("new_editor", func(ctx context.Context, user *models.User) (bool, error) {14 published, err := model.Query[models.Post]().15 Where("user_id", "=", user.ID).16 WhereNotNull("published_at").17 Count(ctx)18 if err != nil {19 return false, err20 }2122 return published >= 10, nil23})1// features/features.go2package features34import (5 "context"67 "go.laravel.com/feature"8 "go.laravel.com/model"910 "app/models"11)1213var NewEditor = feature.Define("new_editor", func(ctx context.Context, user *models.User) (bool, error) {14 published, err := model.Query[models.Post]().15 Where("user_id", "=", user.ID).16 WhereNotNull("published_at").17 Count(ctx)18 if err != nil {19 return false, err20 }2122 return published >= 10, nil23})
If the function returns an error, the check fails with that error, nothing is stored, and the next check runs the function again.
The context also carries the application, so the function may reach your application's services with services.From(ctx) and its configuration with config.From(ctx). The function runs only on a scope's first check, so changing your configuration later doesn't change values that are already stored.
Rich values
Not every feature is on or off. For an experiment with several variants, such as testing three colors for your "Buy now" button, return the variant from the function, in any type that encoding/json can encode. The type's zero value, such as "" or a nil pointer, means the feature is inactive:
1// features/features.go2type ButtonColor string34const (5 BlueSapphire ButtonColor = "blue-sapphire"6 SeafoamGreen ButtonColor = "seafoam-green"7 TartOrange ButtonColor = "tart-orange"8)910var PurchaseButton = feature.Define(11 "purchase-button",12 func(ctx context.Context, user *models.User) (ButtonColor, error) {13 colors := []ButtonColor{BlueSapphire, SeafoamGreen, TartOrange}1415 return colors[user.ID%3], nil16 },17)1// features/features.go2type ButtonColor string34const (5 BlueSapphire ButtonColor = "blue-sapphire"6 SeafoamGreen ButtonColor = "seafoam-green"7 TartOrange ButtonColor = "tart-orange"8)910var PurchaseButton = feature.Define(11 "purchase-button",12 func(ctx context.Context, user *models.User) (ButtonColor, error) {13 colors := []ButtonColor{BlueSapphire, SeafoamGreen, TartOrange}1415 return colors[user.ID%3], nil16 },17)
Laravel stores a rich value as JSON, such as "seafoam-green". If a stored value no longer decodes into the feature's type, such as after you change the type from a string to a struct, Laravel runs the function again and stores the new result.
Checking features
Every check names a feature and a scope, which is the user, team, or other value that the feature decides for. To check a feature, pass the scope to feature.For, then call Active or Value with the request or another context.
Users
A feature checks a scope by calling its FeatureScope method, which returns the key that Laravel stores the scope's values under. Give your User model a FeatureScope method in models/user.go, built with feature.KeyOf:
1// models/user.go2func (u *User) FeatureScope() string {3 return feature.KeyOf("User", u.ID)4}1// models/user.go2func (u *User) FeatureScope() string {3 return feature.KeyOf("User", u.ID)4}
In a handler, pass the logged-in user that r.User returns to feature.For, and call Active:
1package servers23import (4 "go.laravel.com/feature"5 "go.laravel.com/web"67 "app/features"8 "app/handlers/servers/v1"9 "app/handlers/servers/v2"10 "app/models"11)1213func Index(r *web.Request) *web.Response {14 user := r.User[models.User]()15 active, err := feature.For(user).Active(r, features.NewAPI)16 if err != nil {17 return web.Fail(err)18 }19 if active {20 return v2.Index(r)21 }2223 return v1.Index(r)24}1package servers23import (4 "go.laravel.com/feature"5 "go.laravel.com/web"67 "app/features"8 "app/handlers/servers/v1"9 "app/handlers/servers/v2"10 "app/models"11)1213func Index(r *web.Request) *web.Response {14 user := r.User[models.User]()15 active, err := feature.For(user).Active(r, features.NewAPI)16 if err != nil {17 return web.Fail(err)18 }19 if active {20 return v2.Index(r)21 }2223 return v1.Index(r)24}
Use Value to get the typed value the function returned, whether a bool or a rich value:
1color, err := feature.For(user).Value(r, features.PurchaseButton)2if err != nil {3 return web.Fail(err)4}56if color == "" {7 // Don't show the button...8} else {9 // Show the button in this color...10}1color, err := feature.For(user).Value(r, features.PurchaseButton)2if err != nil {3 return web.Fail(err)4}56if color == "" {7 // Don't show the button...8} else {9 // Show the button in this color...10}
Laravel keeps each value in memory for the rest of the request, so checking the same feature several times for one user reads the store only once. The next request reads from the store again. A command or a queued job checks features with the ctx it receives, and each run of a command and each attempt of a job reads the store again.
Teams and other scopes
To scope a feature to a whole team, such as a new billing page that every member of a team should see together, give your Team model a FeatureScope method too:
1// models/team.go2func (t *Team) FeatureScope() string {3 return feature.KeyOf("Team", t.ID)4}1// models/team.go2func (t *Team) FeatureScope() string {3 return feature.KeyOf("Team", t.ID)4}
Pass feature.KeyOf a short kind that never changes, such as "Team". Changing the kind orphans every value already stored for your teams.
A team feature's function takes a *models.Team. For example, this feature enables the new billing page for teams with 50 seats or more, and for one in a hundred smaller teams:
1var BillingV2 = feature.Define("billing_v2", func(ctx context.Context, team *models.Team) (bool, error) {2 return team.Seats >= 50 || lottery.Odds(1, 100).Draw(ctx), nil3})1var BillingV2 = feature.Define("billing_v2", func(ctx context.Context, team *models.Team) (bool, error) {2 return team.Seats >= 50 || lottery.Odds(1, 100).Draw(ctx), nil3})
Then check the feature for a team you've loaded:
1active, err := feature.For(team).Active(r, features.BillingV2)2if err != nil {3 return web.Fail(err)4}5if active {6 return web.Redirect("/billing/v2")7}1active, err := feature.For(team).Active(r, features.BillingV2)2if err != nil {3 return web.Fail(err)4}5if active {6 return web.Redirect("/billing/v2")7}
Each feature is typed to its scope, so checking a team feature for a user doesn't compile.
Guests
When nobody is logged in, r.User returns a nil user, so the handlers above also work on pages that guests may see. A feature is inactive for a nil user, and Laravel doesn't run the feature's function. To decide a feature for guests as well, call ForGuests where you define the feature. Laravel then runs the function with a nil user for guests, and every guest shares one stored value:
1var HolidayBanner = feature.Define(2 "holiday_banner",3 func(ctx context.Context, user *models.User) (bool, error) {4 return user == nil || !user.IsStaff, nil5 },6).ForGuests()1var HolidayBanner = feature.Define(2 "holiday_banner",3 func(ctx context.Context, user *models.User) (bool, error) {4 return user == nil || !user.IsStaff, nil5 },6).ForGuests()
Application-wide features
When a feature has one value for everyone, such as a banner that announces scheduled maintenance, define it with a function that takes feature.Global in place of a scope:
1var MaintenanceBanner = feature.Define(2 "maintenance_banner",3 func(ctx context.Context, _ feature.Global) (bool, error) {4 return false, nil5 },6)1var MaintenanceBanner = feature.Define(2 "maintenance_banner",3 func(ctx context.Context, _ feature.Global) (bool, error) {4 return false, nil5 },6)
Check and update application-wide features with the feature package's top-level functions, which take no scope:
1active, err := feature.Active(r, features.MaintenanceBanner)2if err != nil {3 return web.Fail(err)4}56if active {7 // Show the banner...8}1active, err := feature.Active(r, features.MaintenanceBanner)2if err != nil {3 return web.Fail(err)4}56if active {7 // Show the banner...8}
Middleware
To restrict a route to users who have a feature, attach middleware.RequireFeature in your route file. For user-scoped features, it reads the logged-in user from the request automatically; for feature.Global features, it checks the global scope. When the feature is inactive, Laravel responds with 400 Bad Request:
1package routes23import (4 "go.laravel.com/config"5 "go.laravel.com/middleware"6 "go.laravel.com/routing"78 "app/features"9 "app/handlers/servers"10)1112func API(route *routing.Router, cfg *config.Config) {13 route.Middleware(middleware.RequireFeature(features.NewAPI)).14 Get("/servers", servers.Index)15}1package routes23import (4 "go.laravel.com/config"5 "go.laravel.com/middleware"6 "go.laravel.com/routing"78 "app/features"9 "app/handlers/servers"10)1112func API(route *routing.Router, cfg *config.Config) {13 route.Middleware(middleware.RequireFeature(features.NewAPI)).14 Get("/servers", servers.Index)15}
To require several features, attach one RequireFeature for each. To return a different response when the feature is inactive, such as a redirect to an upgrade page, pass a handler to Otherwise, which runs in place of the route's handler:
1route.Middleware(2 middleware.RequireFeature(features.NewAPI).Otherwise(func(r *web.Request) *web.Response {3 return web.Redirect("/upgrade")4 }),5).Get("/servers", servers.Index)1route.Middleware(2 middleware.RequireFeature(features.NewAPI).Otherwise(func(r *web.Request) *web.Response {3 return web.Redirect("/upgrade")4 }),5).Get("/servers", servers.Index)
For a custom scope such as a team, chain For with a function that resolves the scope from the request:
1route.Middleware(2 middleware.RequireFeature(features.BillingV2).For(func(r *web.Request) (*models.Team, error) {3 team, err := model.FromRoute[models.Team](r, "team")45 return &team, err6 }),7).Get("/teams/{team}/billing", billing.Show)1route.Middleware(2 middleware.RequireFeature(features.BillingV2).For(func(r *web.Request) (*models.Team, error) {3 team, err := model.FromRoute[models.Team](r, "team")45 return &team, err6 }),7).Get("/teams/{team}/billing", billing.Show)
Sharing features with pages
Your pages often need feature values to show or hide parts of the UI, such as a link or a button's color. All returns the value of every feature of the scope's type, keyed by stored name. An inactive feature is false and a rich value is the variant itself, such as "seafoam-green", so the map encodes as JSON that your pages can read:
1{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }1{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }
If your application uses Inertia, add the map to the props that the share function in bootstrap/app.go returns, so every page receives it:
1// bootstrap/app.go2func share(r *web.Request) (inertia.Props, error) {3 user := models.CurrentUser(r)45 flags, err := feature.For(user).All(r)6 if err != nil {7 return nil, err8 }910 return inertia.Props{11 "name": config.From(r).App.Name,12 "auth.user": user,13 "features": flags,14 }, nil15}1// bootstrap/app.go2func share(r *web.Request) (inertia.Props, error) {3 user := models.CurrentUser(r)45 flags, err := feature.For(user).All(r)6 if err != nil {7 return nil, err8 }910 return inertia.Props{11 "name": config.From(r).App.Name,12 "auth.user": user,13 "features": flags,14 }, nil15}
The map from feature.For(user).All leaves out application-wide features. If your pages need those too, add the map that feature.All(r) returns.
If your pages are views, every view has a built-in feature function that checks a feature by its stored name for the logged-in user, or globally for an application-wide feature. An inactive feature returns its type's zero value (such as false or ""), a rich value returns the value itself, and a name that no feature has fails the render:
1{{if feature "new_api"}}2 <a href="/api/docs">Try the new API</a>3{{end}}45{{if eq (feature "purchase-button") "tart-orange"}}6 <button class="bg-orange-500">Buy now</button>7{{end}}1{{if feature "new_api"}}2 <a href="/api/docs">Try the new API</a>3{{end}}45{{if eq (feature "purchase-button") "tart-orange"}}6 <button class="bg-orange-500">Buy now</button>7{{end}}
For a feature scoped to another model, such as a team, or in a mail view that has no logged-in user, pass the scope as the second argument:
1{{if feature "billing_v2" .Team}}2 <a href="/billing">Manage billing</a>3{{end}}1{{if feature "billing_v2" .Team}}2 <a href="/billing">Manage billing</a>3{{end}}
Hiding a link or button doesn't protect the route behind it. Always check the feature in the route's handler too, or guard the route with RequireFeature.
Eager loading
When you render a list of scopes, such as a table of teams, and check a feature for each one, Laravel would query the store once per team. To read every team's value in one query, call feature.Load with the teams before the loop:
1if err := feature.Load(r, features.BillingV2, teams...); err != nil {2 return web.Fail(err)3}45for _, team := range teams {6 billing, err := feature.For(team).Active(r, features.BillingV2)7 if err != nil {8 return web.Fail(err)9 }1011 // ...12}1if err := feature.Load(r, features.BillingV2, teams...); err != nil {2 return web.Fail(err)3}45for _, team := range teams {6 billing, err := feature.For(team).Active(r, features.BillingV2)7 if err != nil {8 return web.Fail(err)9 }1011 // ...12}
Before hooks
Sometimes you need to override a feature for a while without losing its stored values. For example, you may find a bug in a new checkout halfway through its rollout, and want to hide the checkout from everyone except staff while you fix it. A before hook runs on every check, before Laravel reads the stored value, so it can decide the check without changing what's stored. Add one to the feature with Before. In this example, only staff see the new checkout while CHECKOUT_PAUSED is true in your .env file:
1// features/features.go2var NewCheckout = feature.Define(3 "new_checkout",4 func(ctx context.Context, user *models.User) (bool, error) {5 return lottery.Odds(1, 10).Draw(ctx), nil6 },7).Before(func(ctx context.Context, user *models.User) (bool, bool) {8 if os.Getenv("CHECKOUT_PAUSED") != "true" {9 return false, false10 }1112 return user.IsStaff, true13})1// features/features.go2var NewCheckout = feature.Define(3 "new_checkout",4 func(ctx context.Context, user *models.User) (bool, error) {5 return lottery.Odds(1, 10).Draw(ctx), nil6 },7).Before(func(ctx context.Context, user *models.User) (bool, bool) {8 if os.Getenv("CHECKOUT_PAUSED") != "true" {9 return false, false10 }1112 return user.IsStaff, true13})
The hook returns a value and whether that value decides the check. When it reports true, the check returns the hook's value and the store keeps the value it had. When it reports false, the stored value decides, so once you unset CHECKOUT_PAUSED, every user gets their stored value back. Laravel reads .env into the process's environment when the application starts, so os.Getenv sees its variables.
Updating values
You may update a scope's stored value yourself, such as to give a customer early access to the new API, from a handler, a command, or a job:
1flags := feature.For(user)23err := flags.Activate(r, features.NewAPI)4err = flags.ActivateWith(r, features.PurchaseButton, features.TartOrange)5err = flags.Deactivate(r, features.NewAPI)6err = flags.Forget(r, features.PurchaseButton)1flags := feature.For(user)23err := flags.Activate(r, features.NewAPI)4err = flags.ActivateWith(r, features.PurchaseButton, features.TartOrange)5err = flags.Deactivate(r, features.NewAPI)6err = flags.Forget(r, features.PurchaseButton)
Use Activate for features that return bool, and ActivateWith for features with a rich value. Forget deletes the stored value, so the next check runs the function again. For application-wide features, call the feature package's functions of the same names, such as feature.Deactivate(r, features.MaintenanceBanner).
Every scope at once
Once a feature is ready for everyone, or an experiment has a winner, call feature.ForEveryone to update every stored value of the feature at once:
1err := feature.ForEveryone().Activate(r, features.NewAPI)23err = feature.ForEveryone().ActivateWith(r, features.PurchaseButton, features.SeafoamGreen)1err := feature.ForEveryone().Activate(r, features.NewAPI)23err = feature.ForEveryone().ActivateWith(r, features.PurchaseButton, features.SeafoamGreen)
Activate, ActivateWith, and Deactivate change only values that are already stored. A user who hasn't been checked yet still gets the function's result on their first check, so update the function too when you finish a rollout. Forget deletes every stored value of the feature, so every scope runs the function again on its next check.
Purging features
The feature:purge command deletes the stored values of the features you name. Purging a feature that your code still defines makes every scope run its function again on the next check, and purging a feature you removed cleans up the values it left behind:
1laravel feature:purge new_api purchase-button1laravel feature:purge new_api purchase-button
Running feature:purge with no names purges every stored feature, so every feature is decided again. To keep some features, pass --except once for each feature you keep. You may also pass --except-defined, such as during a deploy, to purge only the features that are no longer in Options.Features:
1laravel feature:purge --except-defined1laravel feature:purge --except-defined
Features by name
An admin dashboard or API receives feature names as text rather than as your Go variables. Call feature.Find to look up a feature by its stored name. It returns the feature as a feature.Definition, and reports false when your application doesn't define a feature with that name. ValueOf and Set take a Definition and work with untyped values, such as JSON from a request.
For example, this handler sets a feature for a user at PUT /admin/users/{user}/features. Protect the route so that only admins reach it, as the authorization guide describes:
1package admin23import (4 "net/http"56 "go.laravel.com/feature"7 "go.laravel.com/model"8 "go.laravel.com/web"910 "app/models"11)1213func UpdateFeature(r *web.Request) *web.Response {14 type featureInput struct {15 Name string `json:"name"`16 Value any `json:"value"`17 }18 input, err := r.Bind[featureInput]()19 if err != nil {20 return web.Fail(err)21 }2223 flag, ok := feature.Find(r, input.Name)24 if !ok {25 return web.Abort(http.StatusNotFound)26 }2728 user, err := model.FromRoute[models.User](r, "user")29 if err != nil {30 return web.Fail(err)31 }3233 if err := feature.For(&user).Set(r, flag, input.Value); err != nil {34 return web.Fail(err)35 }3637 return web.NoContent()38}1package admin23import (4 "net/http"56 "go.laravel.com/feature"7 "go.laravel.com/model"8 "go.laravel.com/web"910 "app/models"11)1213func UpdateFeature(r *web.Request) *web.Response {14 type featureInput struct {15 Name string `json:"name"`16 Value any `json:"value"`17 }18 input, err := r.Bind[featureInput]()19 if err != nil {20 return web.Fail(err)21 }2223 flag, ok := feature.Find(r, input.Name)24 if !ok {25 return web.Abort(http.StatusNotFound)26 }2728 user, err := model.FromRoute[models.User](r, "user")29 if err != nil {30 return web.Fail(err)31 }3233 if err := feature.For(&user).Set(r, flag, input.Value); err != nil {34 return web.Fail(err)35 }3637 return web.NoContent()38}
The value must be what the feature's type encodes to, such as "seafoam-green" for features.SeafoamGreen, and false or null deactivates the feature. When the value doesn't fit the feature's type, Laravel responds with a 422 that names the feature and stores nothing. To list every feature your application defines, call feature.Defined(r).
Feature stores of your own
To keep feature values in another backend, such as Redis or an external feature flag service, implement the feature.Store interface. Each value is a feature's JSON for one scope, keyed by the feature's name and the scope's key, so your store keeps the bytes and returns them unchanged:
1type Store interface {2 Get(ctx context.Context, features, scopes []string) (map[feature.Pair][]byte, error)3 Add(ctx context.Context, feature, scope string, value []byte) ([]byte, error)4 Set(ctx context.Context, feature, scope string, value []byte) error5 UpdateAll(ctx context.Context, feature string, value []byte) error6 Forget(ctx context.Context, feature, scope string) error7 Purge(ctx context.Context, features ...string) error8 Names(ctx context.Context) ([]string, error)9}1type Store interface {2 Get(ctx context.Context, features, scopes []string) (map[feature.Pair][]byte, error)3 Add(ctx context.Context, feature, scope string, value []byte) ([]byte, error)4 Set(ctx context.Context, feature, scope string, value []byte) error5 UpdateAll(ctx context.Context, feature string, value []byte) error6 Forget(ctx context.Context, feature, scope string) error7 Purge(ctx context.Context, features ...string) error8 Names(ctx context.Context) ([]string, error)9}
Each method's doc comment says what the method must do. Add must check and store in one atomic step, such as an insert that ignores a conflict on a unique key, so that concurrent first-time checks agree on one value.
Register the store by name in the Register option of bootstrap/app.go. In this example, stores is a package of your own that holds the Redis store:
1return laravel.Options{2 // ...34 Features: features.All,5 Register: func(app *laravel.Registrar) error {6 app.FeatureStore("redis", stores.NewRedisFeatureStore(7 app.Env().String("REDIS_ADDR", "127.0.0.1:6379"),8 ))910 return nil11 },12}1return laravel.Options{2 // ...34 Features: features.All,5 Register: func(app *laravel.Registrar) error {6 app.FeatureStore("redis", stores.NewRedisFeatureStore(7 app.Env().String("REDIS_ADDR", "127.0.0.1:6379"),8 ))910 return nil11 },12}
Then select the store in .env with FEATURE_STORE=redis. Because FEATURE_STORE chooses the store, your tests stay on the memory store they select for you. A package registers a store the same way with app.FeatureStore inside its Register method. To learn more, check out the packages guide's section on what a package can add.
Testing
Tests use the memory store, and each test builds its own application, so every test starts with an empty store and needs no features table.
To pin a feature's value for every scope for the rest of the test, call feature.Fake with the client's context:
1package feature_test23import (4 "testing"56 "go.laravel.com/feature"78 "app/features"9 "app/tests"10)1112func TestTheNewAPIListsServers(t *testing.T) {13 client := tests.New(t)14 feature.Fake(client.Context(), features.NewAPI, true)15 feature.Fake(client.Context(), features.PurchaseButton, features.TartOrange)1617 client.Get("/api/servers").AssertOK()18}1package feature_test23import (4 "testing"56 "go.laravel.com/feature"78 "app/features"9 "app/tests"10)1112func TestTheNewAPIListsServers(t *testing.T) {13 client := tests.New(t)14 feature.Fake(client.Context(), features.NewAPI, true)15 feature.Fake(client.Context(), features.PurchaseButton, features.TartOrange)1617 client.Get("/api/servers").AssertOK()18}
To change a value partway through a test, call feature.Fake again. To return a different value for each scope, call feature.FakeUsing with a function that takes the feature's scope, such as a *models.User, and returns the scope's value:
1feature.FakeUsing(client.Context(), features.NewAPI, func(user *models.User) bool {2 return user.ID == 13})1feature.FakeUsing(client.Context(), features.NewAPI, func(user *models.User) bool {2 return user.ID == 13})
For features that draw a lottery, you may also build the client with laraveltest.Lottery(lottery.AlwaysWin) or laraveltest.Lottery(lottery.AlwaysLose). In HTTP tests where a specific feature matters, prefer feature.Fake over lottery.Fix, because the session middleware may use up fixed draws before your handler runs.