Feature Flags
- Introduction
- Configuration
- Defining features
- Rich values
- Checking features
- Updating values
- Flags by name
- Custom stores
- Testing
Introduction
Feature flags let you roll out new functionality gradually without redeploying at each step. You can enable a new API for staff first, expand it to one customer in a hundred, and eventually turn it on for everyone. You can also run A/B experiments, such as showing each user one of three button colors and keeping the version that converts best.
In Laravel, a feature flag is a Rust function that determines the initial value for a user, a team, or the entire application. Laravel stores that resolved value so the user receives a consistent experience on every subsequent request until you explicitly update or purge it.
Configuration
By default, Laravel persists feature values in your database so every server agrees on each user's flag state and values survive deployments. Configure feature storage with these environment variables:
| Variable | Default | Purpose |
|---|---|---|
FEATURE_STORE |
database |
database, memory, or the name of a custom store. |
DB_FEATURE_CONNECTION |
Default connection | Database connection used by the database store. |
DB_FEATURE_TABLE |
features |
Table name used by the database store. |
The memory store keeps resolved values in each process's memory and discards them on restart. It is ideal for local development and tests, and is used automatically when your application has no database configured.
The features table
The database store requires a features table, which is not created by default. Create it in a migration with laravel::feature::table!():
1// database/migrations/2026_01_01_000000_create_features_table.rs2laravel::feature::table!();1// database/migrations/2026_01_01_000000_create_features_table.rs2laravel::feature::table!();
If you'd like to customize the table, such as using a different table name or adding a column, replace the macro with the migration it stands for and edit it:
1// database/migrations/2026_01_01_000000_create_features_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("features", |table| {7 table.id();8 table.string("name");9 table.string("scope");10 table.text("value");11 table.timestamps();12 table.unique(["name", "scope"]);13 })14 .await15}1// database/migrations/2026_01_01_000000_create_features_table.rs2use laravel::db::AnyTransaction;34pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {5 tx.schema()6 .create("features", |table| {7 table.id();8 table.string("name");9 table.string("scope");10 table.text("value");11 table.timestamps();12 table.unique(["name", "scope"]);13 })14 .await15}
Keep the unique index on name and scope so concurrent first-time checks for the same user always converge on a single stored value.
Defining features
Define a feature by annotating a function with #[flag]. Laravel discovers every #[flag] function automatically without manual registration, and you can organize them together in src/features.rs. The function receives the scope it evaluates for (typically &User) and returns whether the feature is active. For example, this flag enables a new API for staff and 1% of other users:
1// src/features.rs2use laravel::feature::flag;3use laravel::lottery::Lottery;45use crate::models::User;67#[flag]8pub fn new_api(user: &User) -> bool {9 user.is_staff || Lottery::odds(1, 100).draw()10}1// src/features.rs2use laravel::feature::flag;3use laravel::lottery::Lottery;45use crate::models::User;67#[flag]8pub fn new_api(user: &User) -> bool {9 user.is_staff || Lottery::odds(1, 100).draw()10}
The function runs once per user on their first check, and Laravel stores what it returns. Subsequent checks read the stored value directly without invoking the function again, so each user gets a single lottery draw and keeps that outcome.
#[flag] generates a unit struct with the same name as the function, which you pass when checking the feature. Misspelling a feature name fails at compile time.
Because #[flag] defines a unit struct with the function's name, writing let new_api = user.features().active(new_api).await? will not compile because Rust treats new_api in the let pattern as the struct. Import the module instead and reference features::new_api.
Stored names
Laravel stores each flag under its function name unless you override it with name. Because renaming a function would orphan existing stored rows, preserve the original stored name when refactoring:
1use laravel::feature::flag;23use crate::models::User;45#[flag(name = "new_api")]6pub fn new_servers_api(user: &User) -> bool {7 user.is_staff8}1use laravel::feature::flag;23use crate::models::User;45#[flag(name = "new_api")]6pub fn new_servers_api(user: &User) -> bool {7 user.is_staff8}
You can also use name to give a flag a cleaner identifier for templates or admin pages, such as purchase-button.
Async features, services, and config
A #[flag] function may be async and return a laravel::Result, allowing it to query the database or external services. For example, this flag enables a new editor for authors with at least ten published posts:
1use laravel::feature::flag;23use crate::models::{Post, User};45#[flag]6pub async fn new_editor(user: &User) -> laravel::Result<bool> {7 let published = Post::query()8 .filter(Post::user_id.eq(user.id))9 .filter(!Post::published_at.is_null())10 .count()11 .await?;1213 Ok(published >= 10)14}1use laravel::feature::flag;23use crate::models::{Post, User};45#[flag]6pub async fn new_editor(user: &User) -> laravel::Result<bool> {7 let published = Post::query()8 .filter(Post::user_id.eq(user.id))9 .filter(!Post::published_at.is_null())10 .count()11 .await?;1213 Ok(published >= 10)14}
If the function returns an error, the check propagates that error without storing anything, and the next check invokes the function again.
After the scope parameter, a flag function may also accept Inject<T> services and Section<T> config sections in any order. Laravel resolves these only when the function runs on a scope's first check, so changing configuration later does not alter already-stored values.
Rich values
Not every feature is a simple boolean. For multi-variant experiments (such as testing three colors for a "Buy now" button), return Option<T> where Some(value) is active with that variant and None is inactive. The value type must implement Serialize, Deserialize, and Clone:
1use laravel::feature::flag;2use serde::{Deserialize, Serialize};34use crate::models::User;56#[derive(Clone, Serialize, Deserialize)]7#[serde(rename_all = "kebab-case")]8pub enum ButtonColor {9 BlueSapphire,10 SeafoamGreen,11 TartOrange,12}1314#[flag(name = "purchase-button")]15pub fn purchase_button(user: &User) -> Option<ButtonColor> {16 Some(match user.id % 3 {17 0 => ButtonColor::BlueSapphire,18 1 => ButtonColor::SeafoamGreen,19 _ => ButtonColor::TartOrange,20 })21}1use laravel::feature::flag;2use serde::{Deserialize, Serialize};34use crate::models::User;56#[derive(Clone, Serialize, Deserialize)]7#[serde(rename_all = "kebab-case")]8pub enum ButtonColor {9 BlueSapphire,10 SeafoamGreen,11 TartOrange,12}1314#[flag(name = "purchase-button")]15pub fn purchase_button(user: &User) -> Option<ButtonColor> {16 Some(match user.id % 3 {17 0 => ButtonColor::BlueSapphire,18 1 => ButtonColor::SeafoamGreen,19 _ => ButtonColor::TartOrange,20 })21}
Laravel stores rich values as JSON, such as "seafoam-green". If a stored value can no longer be deserialized into the expected type (for example, after you remove an enum variant), Laravel re-runs the flag function and stores the new result.
Checking features
Every check pairs a feature with a scope, such as a user or a team. Call .features() on the scope (provided by the HasFeatures trait in the prelude), then call active or value.
Users
User models support .features() automatically. In a handler, extract Authenticated<User> and call active:
1use laravel::prelude::*;23use crate::features;4use crate::models::User;56pub async fn index(user: Authenticated<User>) -> laravel::Result<Response> {7 if user.features().active(features::new_api).await? {8 return servers::v2::index().await;9 }1011 servers::v1::index().await12}1use laravel::prelude::*;23use crate::features;4use crate::models::User;56pub async fn index(user: Authenticated<User>) -> laravel::Result<Response> {7 if user.features().active(features::new_api).await? {8 return servers::v2::index().await;9 }1011 servers::v1::index().await12}
Use value to retrieve the typed result returned by the flag function, whether bool or a rich value:
1match user.features().value(features::purchase_button).await? {2 Some(color) => {3 // Show the button in this color...4 }5 None => {6 // Don't show the button...7 }8}1match user.features().value(features::purchase_button).await? {2 Some(color) => {3 // Show the button in this color...4 }5 None => {6 // Don't show the button...7 }8}
Laravel caches each resolved value in memory for the remainder of the current request, so checking the same feature multiple times for the same user queries the store only once. Subsequent requests read from the store again.
Teams and other scopes
To scope a feature to an entire team, such as a new billing page that every team member should see together, implement HasFeatures on your Team model. feature_key returns the stable identifier Laravel uses to store that team's values:
1use laravel::feature::{HasFeatures, ScopeKey};23use crate::models::Team;45impl HasFeatures for Team {6 fn feature_key(&self) -> ScopeKey {7 ScopeKey::new("Team", self.id)8 }9}1use laravel::feature::{HasFeatures, ScopeKey};23use crate::models::Team;45impl HasFeatures for Team {6 fn feature_key(&self) -> ScopeKey {7 ScopeKey::new("Team", self.id)8 }9}
Use a short, permanent scope kind such as "Team". Changing the scope kind orphans previously stored values for that type.
A team-scoped flag function takes &Team. For example, this flag enables a new billing page for teams with 50 or more seats plus 1% of smaller teams:
1use laravel::feature::flag;2use laravel::lottery::Lottery;34use crate::models::Team;56#[flag]7pub fn billing_v2(team: &Team) -> bool {8 team.seats >= 50 || Lottery::odds(1, 100).draw()9}1use laravel::feature::flag;2use laravel::lottery::Lottery;34use crate::models::Team;56#[flag]7pub fn billing_v2(team: &Team) -> bool {8 team.seats >= 50 || Lottery::odds(1, 100).draw()9}
Check the feature directly on a loaded Team:
1if team.features().active(features::billing_v2).await? {2 return Ok(Redirect::to("/billing/v2").into_response());3}1if team.features().active(features::billing_v2).await? {2 return Ok(Redirect::to("/billing/v2").into_response());3}
Each flag is typed to its scope, so checking a team feature on a User fails to compile.
Guests
Flags that take &User evaluate to inactive for guests without running the function. To evaluate a flag for guests as well, accept Option<&User>. Laravel passes None for guests, and all guests share a single stored value:
1use laravel::feature::flag;23use crate::models::User;45#[flag]6pub fn holiday_banner(user: Option<&User>) -> bool {7 user.is_none_or(|user| !user.is_staff)8}1use laravel::feature::flag;23use crate::models::User;45#[flag]6pub fn holiday_banner(user: Option<&User>) -> bool {7 user.is_none_or(|user| !user.is_staff)8}
In handlers accessible to both signed-in users and guests, extract Auth<User> and call .features() directly on the Option<User> returned by auth.user() (when None, Laravel evaluates the flag for a guest):
1use laravel::auth::Auth;2use laravel::prelude::*;34use crate::features;5use crate::models::User;67pub async fn home(auth: Auth<User>) -> laravel::Result<Response> {8 let user = auth.user().await?;910 if user.features().active(features::holiday_banner).await? {11 // Show the banner...12 }1314 Ok(view("home", ()).into_response())15}1use laravel::auth::Auth;2use laravel::prelude::*;34use crate::features;5use crate::models::User;67pub async fn home(auth: Auth<User>) -> laravel::Result<Response> {8 let user = auth.user().await?;910 if user.features().active(features::holiday_banner).await? {11 // Show the banner...12 }1314 Ok(view("home", ()).into_response())15}
When you want to check or update the guest scope directly without an Option<User>, call feature::guest::<User>().
Application-wide features
When a feature has a single value for everyone, such as a scheduled maintenance banner, define a #[flag] function with no scope parameter:
1use laravel::feature::flag;23#[flag]4pub fn maintenance_banner() -> bool {5 false6}1use laravel::feature::flag;23#[flag]4pub fn maintenance_banner() -> bool {5 false6}
Check and update application-wide features using the top-level functions in laravel::feature:
1use laravel::feature;23if feature::active(features::maintenance_banner).await? {4 // ...5}1use laravel::feature;23if feature::active(features::maintenance_banner).await? {4 // ...5}
Middleware
To restrict a route to users who have a feature enabled, attach RequireFeature middleware. When the feature is inactive, Laravel responds with 400 Bad Request:
1use laravel::feature::RequireFeature;2use laravel::prelude::*;34use crate::features;56pub fn routes(route: &mut Router) {7 route8 .get("/api/servers", servers::index)9 .middleware(RequireFeature::new(features::new_api));10}1use laravel::feature::RequireFeature;2use laravel::prelude::*;34use crate::features;56pub fn routes(route: &mut Router) {7 route8 .get("/api/servers", servers::index)9 .middleware(RequireFeature::new(features::new_api));10}
To require multiple features, attach one RequireFeature per feature. To return a custom response when the feature is inactive, chain .otherwise(..) with a handler:
1route2 .get("/servers", servers::index)3 .middleware(4 RequireFeature::new(features::new_api)5 .otherwise(async || Redirect::to("/upgrade")),6 );1route2 .get("/servers", servers::index)3 .middleware(4 RequireFeature::new(features::new_api)5 .otherwise(async || Redirect::to("/upgrade")),6 );
RequireFeature supports user features and application-wide features. For team-scoped features, write custom middleware that resolves the team and calls team.features().active(..).
Sharing features with pages
Frontend pages frequently need feature flags to show or hide UI elements. Calling .all() returns every feature defined for that scope type as a JSON object keyed by stored name, with inactive flags set to false and rich values serialized to JSON:
1{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }1{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }
In an Inertia application, share this object from your middleware's share method so every page receives it:
1// src/http/middleware/handle_inertia_requests.rs2use laravel::inertia::{self, Props, props};3use laravel::prelude::*;45use crate::models::User;67impl inertia::Middleware for HandleInertiaRequests {8 async fn share(&self, request: &Request) -> laravel::Result<Props> {9 let user: Option<User> = request.user().await?;10 let features = user.features().all().await?;1112 Ok(props! {13 features => features,14 })15 }16}1// src/http/middleware/handle_inertia_requests.rs2use laravel::inertia::{self, Props, props};3use laravel::prelude::*;45use crate::models::User;67impl inertia::Middleware for HandleInertiaRequests {8 async fn share(&self, request: &Request) -> laravel::Result<Props> {9 let user: Option<User> = request.user().await?;10 let features = user.features().all().await?;1112 Ok(props! {13 features => features,14 })15 }16}
For server-rendered templates, append ShareFeatures to your web middleware group in src/app.rs:
1use laravel::feature::ShareFeatures;23.with_middleware(|middleware, _| {4 middleware.web(|web| {5 web.append(ShareFeatures::<User>::new());6 });7})1use laravel::feature::ShareFeatures;23.with_middleware(|middleware, _| {4 middleware.web(|web| {5 web.append(ShareFeatures::<User>::new());6 });7})
Templates can then call feature(name) with a flag's stored name. Passing an undefined flag name fails template rendering:
1{% if feature("new_api") %}2 <a href="/api/docs">Try the new API</a>3{% endif %}45{% if feature("purchase-button") == "tart-orange" %}6 <button class="bg-orange-500">Buy now</button>7{% endif %}1{% if feature("new_api") %}2 <a href="/api/docs">Try the new API</a>3{% endif %}45{% if feature("purchase-button") == "tart-orange" %}6 <button class="bg-orange-500">Buy now</button>7{% endif %}
Hiding a link or button in the UI does not protect the route behind it. Always check the feature in the route's handler or guard it with RequireFeature.
Eager loading
When rendering a list of scopes (such as a table of teams) and checking a feature on each, querying one by one causes an N+1 lookup against the store. Call feature::load before the loop to fetch every scope's value in a single query:
1use laravel::feature;23feature::load(features::billing_v2, &teams).await?;45for team in &teams {6 let billing = team.features().active(features::billing_v2).await?;78 // ...9}1use laravel::feature;23feature::load(features::billing_v2, &teams).await?;45for team in &teams {6 let billing = team.features().active(features::billing_v2).await?;78 // ...9}
Updating values
You can update a scope's stored value programmatically (for example, granting a customer early access to a feature) from a handler, command, or job:
1use crate::features::{self, ButtonColor};23user.features().activate(features::new_api).await?;45user.features()6 .activate_with(features::purchase_button, ButtonColor::TartOrange)7 .await?;89user.features().deactivate(features::new_api).await?;10user.features().forget(features::purchase_button).await?;1use crate::features::{self, ButtonColor};23user.features().activate(features::new_api).await?;45user.features()6 .activate_with(features::purchase_button, ButtonColor::TartOrange)7 .await?;89user.features().deactivate(features::new_api).await?;10user.features().forget(features::purchase_button).await?;
Use activate for boolean flags and activate_with for rich-value flags. Calling forget deletes the stored row so the next check re-runs the flag function. For application-wide features, call the matching top-level functions such as feature::deactivate(features::maintenance_banner).await?.
Every scope at once
Once a feature is ready for general release or an experiment has a winner, call feature::everyone() to update every stored entry for that flag at once:
1use laravel::feature;23use crate::features::{self, ButtonColor};45feature::everyone().activate(features::new_api).await?;67feature::everyone()8 .activate_with(features::purchase_button, ButtonColor::SeafoamGreen)9 .await?;1use laravel::feature;23use crate::features::{self, ButtonColor};45feature::everyone().activate(features::new_api).await?;67feature::everyone()8 .activate_with(features::purchase_button, ButtonColor::SeafoamGreen)9 .await?;
activate, activate_with, and deactivate only modify entries already stored in the database. Users who have never been checked will still receive the flag function's result on their first check, so update the function as well when finalizing a rollout. Calling forget deletes every stored entry so all scopes re-evaluate the function on their next check.
Purging features
Use the feature:purge command to delete stored feature rows from the store. Purging a feature that is still defined in your code causes it to be re-computed from its #[flag] function on the next check, while purging a removed feature cleans up its old rows:
1laravel feature:purge new_api purchase-button1laravel feature:purge new_api purchase-button
Running feature:purge with no names purges all stored features so every defined flag is re-evaluated. Pass --except to keep specific names, or pass --except-defined (for example, during deployment) to purge only flags that are no longer defined in your application:
1laravel feature:purge --except-defined1laravel feature:purge --except-defined
Flags by name
An admin dashboard or API receives flag names as strings rather than compile-time #[flag] types. Call feature::find to look up a flag by its stored name as an AnyFlag (returning None if undefined). Every check and mutation method accepts AnyFlag, with rich values passed as JSON.
For example, this handler updates a flag for a user at PUT /admin/users/{user}/flags (protect the route with admin authorization):
1use laravel::feature;2use laravel::http::NoContent;3use laravel::prelude::*;45use crate::models::User;67#[laravel::input]8#[validate(anyone)]9pub struct UpdateFlag {10 #[validate(required)]11 name: String,12 value: Option<serde_json::Value>,13}1415pub async fn update(16 user: User,17 Valid(input): Valid<UpdateFlag>,18) -> laravel::Result<NoContent> {19 let flag = feature::find(&input.name).or_abort(404)?;2021 match input.value {22 Some(value) => user.features().activate_with(flag, value).await?,23 None => user.features().deactivate(flag).await?,24 }2526 Ok(NoContent)27}1use laravel::feature;2use laravel::http::NoContent;3use laravel::prelude::*;45use crate::models::User;67#[laravel::input]8#[validate(anyone)]9pub struct UpdateFlag {10 #[validate(required)]11 name: String,12 value: Option<serde_json::Value>,13}1415pub async fn update(16 user: User,17 Valid(input): Valid<UpdateFlag>,18) -> laravel::Result<NoContent> {19 let flag = feature::find(&input.name).or_abort(404)?;2021 match input.value {22 Some(value) => user.features().activate_with(flag, value).await?,23 None => user.features().deactivate(flag).await?,24 }2526 Ok(NoContent)27}
The JSON value must deserialize into the flag's expected type (such as "seafoam-green" for ButtonColor::SeafoamGreen). An invalid JSON value returns a 422 response naming the flag without modifying the store. To list every flag defined in your application, call feature::defined().
Custom stores
To persist feature flags in another backend, such as Redis or an external feature-flag service, implement laravel::feature::FeatureStore. Values are passed as JSON strings keyed by feature name and scope:
1use laravel::feature::{FeatureStore, ScopeKey, StoredValues};23pub struct RedisFeatureStore;45impl FeatureStore for RedisFeatureStore {6 async fn get_many(7 &self,8 features: &[&str],9 scopes: &[ScopeKey],10 ) -> laravel::Result<StoredValues> {11 // Read every pair's value in one round trip...12 todo!()13 }1415 async fn add(16 &self,17 feature: &str,18 scope: &ScopeKey,19 value: &str,20 ) -> laravel::Result<Option<String>> {21 // Store the value unless the scope has one, returning any existing value...22 todo!()23 }2425 async fn set(26 &self,27 feature: &str,28 scope: &ScopeKey,29 value: &str,30 ) -> laravel::Result<()> {31 // Store the value, replacing any earlier one...32 todo!()33 }3435 async fn update_all(&self, feature: &str, value: &str) -> laravel::Result<()> {36 // Replace every stored value of the feature...37 todo!()38 }3940 async fn forget(&self, feature: &str, scope: &ScopeKey) -> laravel::Result<()> {41 // Delete the scope's value...42 todo!()43 }4445 async fn purge(&self, features: &[&str]) -> laravel::Result<()> {46 // Delete every value of these features...47 todo!()48 }4950 async fn stored_names(&self) -> laravel::Result<Vec<String>> {51 // Return the name of every feature that has a stored value...52 todo!()53 }54}1use laravel::feature::{FeatureStore, ScopeKey, StoredValues};23pub struct RedisFeatureStore;45impl FeatureStore for RedisFeatureStore {6 async fn get_many(7 &self,8 features: &[&str],9 scopes: &[ScopeKey],10 ) -> laravel::Result<StoredValues> {11 // Read every pair's value in one round trip...12 todo!()13 }1415 async fn add(16 &self,17 feature: &str,18 scope: &ScopeKey,19 value: &str,20 ) -> laravel::Result<Option<String>> {21 // Store the value unless the scope has one, returning any existing value...22 todo!()23 }2425 async fn set(26 &self,27 feature: &str,28 scope: &ScopeKey,29 value: &str,30 ) -> laravel::Result<()> {31 // Store the value, replacing any earlier one...32 todo!()33 }3435 async fn update_all(&self, feature: &str, value: &str) -> laravel::Result<()> {36 // Replace every stored value of the feature...37 todo!()38 }3940 async fn forget(&self, feature: &str, scope: &ScopeKey) -> laravel::Result<()> {41 // Delete the scope's value...42 todo!()43 }4445 async fn purge(&self, features: &[&str]) -> laravel::Result<()> {46 // Delete every value of these features...47 todo!()48 }4950 async fn stored_names(&self) -> laravel::Result<Vec<String>> {51 // Return the name of every feature that has a stored value...52 todo!()53 }54}
add must check and insert atomically (such as an insert ignoring unique-key conflicts) so concurrent first-time checks agree on one value. Stores backed by a remote feature flag service can also implement defined_for to expose flags not declared in Rust, which callers can look up via user.features().find(name).
Register your custom store in src/app.rs inside with_services, then select it with FEATURE_STORE=redis:
1Application::configure()2 .with_services(|app| {3 app.features()4 .extend("redis", |_app| async { Ok(RedisFeatureStore) });5 })1Application::configure()2 .with_services(|app| {3 app.features()4 .extend("redis", |_app| async { Ok(RedisFeatureStore) });5 })
Packages can register custom stores inside their service provider's register method via app.features().extend(..).
Testing
Tests use the memory store by default, and each test runs with an isolated application starting from an empty store, so no features table is required.
Use feature::fake to pin a feature's value across all scopes for the remainder of the test:
1use laravel::feature;2use laravel::testing::prelude::*;34use app::features::{self, ButtonColor};56#[laravel::test]7async fn the_new_api_lists_servers(app: Application) {8 feature::fake(features::new_api, true);9 feature::fake(features::purchase_button, Some(ButtonColor::TartOrange));1011 app.get("/api/servers").await.assert_ok();12}1use laravel::feature;2use laravel::testing::prelude::*;34use app::features::{self, ButtonColor};56#[laravel::test]7async fn the_new_api_lists_servers(app: Application) {8 feature::fake(features::new_api, true);9 feature::fake(features::purchase_button, Some(ButtonColor::TartOrange));1011 app.get("/api/servers").await.assert_ok();12}
To return different values per scope, call feature::fake_using with a closure taking the flag's scope parameter (such as &User):
1feature::fake_using(features::new_api, |user| user.id == 1);1feature::fake_using(features::new_api, |user| user.id == 1);
For features using a lottery, you can call Lottery::always_win() or Lottery::always_lose(). In HTTP tests where a specific flag matters, prefer feature::fake over Lottery::fix, because session garbage collection and ShareFeatures may consume fixed lottery draws before your handler runs.