# Feature Flags

- [Introduction](#introduction)
- [Configuration](#storage)
    - [The features table](#the-features-table)
- [Defining features](#defining-features)
    - [Stored names](#stored-names)
    - [Async features, services, and config](#services-and-config)
- [Rich values](#rich-values)
- [Checking features](#checking-features)
    - [Users](#users)
    - [Teams and other scopes](#teams-and-other-scopes)
    - [Guests](#guests)
    - [Application-wide features](#application-wide-features)
    - [Middleware](#middleware)
    - [Sharing features with pages](#sharing-features-with-pages)
    - [Eager loading](#eager-loading)
- [Updating values](#updating-values)
    - [Every scope at once](#every-scope-at-once)
    - [Purging features](#purging-features)
- [Flags by name](#flags-by-name)
- [Custom stores](#custom-stores)
- [Testing](#testing)

<a name="introduction"></a>

## Introduction


機能フラグを使うと、各段階で再デプロイせずに新機能を段階的に公開できます。新しい API をまずスタッフ向けに有効化し、顧客の 100 人に 1 人へ拡大し、最後に全員へ公開できます。また、ユーザーごとに三色のボタンの一つを表示し、最もコンバージョン率の高いものを採用する A/B テストも行えます。


Laravel の機能フラグは、ユーザー、チーム、アプリケーション全体の初期値を決める Rust 関数です。Laravel は解決した値を保存するため、明示的に更新または削除するまで、以後のリクエストでもユーザーに一貫した体験を提供します。

<a name="storage"></a>

## Configuration


デフォルトでは、Laravel は機能の値をデータベースに永続化します。これにより、すべてのサーバーで各ユーザーのフラグ状態が一致し、デプロイ後も値が保持されます。次の環境変数で機能ストレージを設定します。

| 変数 | デフォルト | 用途 |
| --- | --- | --- |
| `FEATURE_STORE` | `database` | `database`、`memory`、または [custom store](#custom-stores) の名前。 |
| `DB_FEATURE_CONNECTION` | デフォルト接続 | `database` ストアが使用するデータベース接続。 |
| `DB_FEATURE_TABLE` | `features` | `database` ストアが使用するテーブル名。 |


`memory` ストアは解決した値を各プロセスのメモリに保持し、再起動時に破棄します。ローカル開発やテストに適しており、アプリケーションにデータベースが設定されていない場合は自動的に使われます。

<a name="the-features-table"></a>

### The features table


`database` ストアには `features` テーブルが必要ですが、デフォルトでは作成されません。[migration](/ja/rust/docs/migrations#framework-tables) で `laravel::feature::table!()` を使って作成します。

```rust
// database/migrations/2026_01_01_000000_create_features_table.rs
laravel::feature::table!();
```


別のテーブル名を使う、カラムを追加するなどのカスタマイズを行うには、マクロをその展開先のマイグレーションに置き換えて編集します。

```rust
// database/migrations/2026_01_01_000000_create_features_table.rs
use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    tx.schema()
        .create("features", |table| {
            table.id();
            table.string("name");
            table.string("scope");
            table.text("value");
            table.timestamps();
            table.unique(["name", "scope"]);
        })
        .await
}
```


同じユーザーに対する初回チェックが並行して実行されても、一つの保存値に収束するように、`name` と `scope` のユニークインデックスを維持してください。

<a name="defining-features"></a>

## Defining features


関数に `#[flag]` を付けて機能を定義します。Laravel は手動登録なしですべての `#[flag]` 関数を自動検出するため、`src/features.rs` にまとめて配置できます。関数は評価対象のスコープ（通常は `&User`）を受け取り、機能が有効かどうかを返します。次のフラグはスタッフとその他のユーザーの 1% に新しい API を有効化します。

```rust
// src/features.rs
use laravel::feature::flag;
use laravel::lottery::Lottery;

use crate::models::User;

#[flag]
pub fn new_api(user: &User) -> bool {
    user.is_staff || Lottery::odds(1, 100).draw()
}
```


関数はユーザーごとの初回チェックで一度実行され、Laravel が戻り値を保存します。以後は関数を再実行せず保存値を直接読むため、各ユーザーは一度だけ [lottery](/ja/rust/docs/lottery) の抽選を行い、その結果を維持します。


`#[flag]` は関数と同名のユニット構造体を生成し、機能のチェック時に渡します。機能名を誤るとコンパイル時にエラーになります。

> [!NOTE]
> `#[flag]` は関数名でユニット構造体を定義するため、`let new_api = user.features().active(new_api).await?` はコンパイルできません。Rust が `let` パターン内の `new_api` を構造体として扱うためです。代わりにモジュールをインポートし、`features::new_api` として参照してください。

<a name="stored-names"></a>

### Stored names


`name` で上書きしない限り、Laravel は関数名でフラグを保存します。関数名を変更すると既存の保存行が参照されなくなるため、リファクタリング時は元の保存名を維持してください。

```rust
use laravel::feature::flag;

use crate::models::User;

#[flag(name = "new_api")]
pub fn new_servers_api(user: &User) -> bool {
    user.is_staff
}
```


`name` を使うと、`purchase-button` など、テンプレートや管理画面で扱いやすい識別子も指定できます。

<a name="services-and-config"></a>

### Async features, services, and config


`#[flag]` 関数は `async` にでき、`laravel::Result` を返せるため、データベースや外部サービスに問い合わせられます。次のフラグは、公開済み記事が 10 件以上ある著者に新しいエディターを有効化します。

```rust
use laravel::feature::flag;

use crate::models::{Post, User};

#[flag]
pub async fn new_editor(user: &User) -> laravel::Result<bool> {
    let published = Post::query()
        .filter(Post::user_id.eq(user.id))
        .filter(!Post::published_at.is_null())
        .count()
        .await?;

    Ok(published >= 10)
}
```


関数がエラーを返すと、何も保存せずにそのエラーを伝播し、次のチェックで関数を再び呼び出します。


スコープ引数の後には、`Inject<T>` の [services](/ja/rust/docs/container#in-handlers) と `Section<T>` の [config sections](/ja/rust/docs/configuration#your-own-config-sections) を任意の順序で受け取れます。Laravel がこれらを解決するのは、スコープの初回チェックで関数を実行するときだけです。そのため、後から設定を変えても保存済みの値は変わりません。

<a name="rich-values"></a>

## Rich values


すべての機能が単純な真偽値とは限りません。「今すぐ購入」ボタンの三色を試すような複数バリエーションの実験では `Option<T>` を返します。`Some(value)` はそのバリエーションで有効、`None` は無効を表します。値の型は `Serialize`、`Deserialize`、`Clone` を実装する必要があります。

```rust
use laravel::feature::flag;
use serde::{Deserialize, Serialize};

use crate::models::User;

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ButtonColor {
    BlueSapphire,
    SeafoamGreen,
    TartOrange,
}

#[flag(name = "purchase-button")]
pub fn purchase_button(user: &User) -> Option<ButtonColor> {
    Some(match user.id % 3 {
        0 => ButtonColor::BlueSapphire,
        1 => ButtonColor::SeafoamGreen,
        _ => ButtonColor::TartOrange,
    })
}
```


Laravel は複合的な値を `"seafoam-green"` などの JSON として保存します。列挙型のバリアントを削除した場合など、保存値を期待する型にデシリアライズできなくなると、フラグ関数を再実行して新しい結果を保存します。

<a name="checking-features"></a>

## Checking features


各チェックは、機能とユーザーやチームなどのスコープを組み合わせます。スコープで `.features()` を呼び、その後に `active` または `value` を呼びます。このメソッドは prelude の `HasFeatures` トレイトが提供します。

<a name="users"></a>

### Users


ユーザーモデルは `.features()` を自動的にサポートします。ハンドラーで `Authenticated<User>` を抽出し、`active` を呼び出します。

```rust
use laravel::prelude::*;

use crate::features;
use crate::models::User;

pub async fn index(user: Authenticated<User>) -> laravel::Result<Response> {
    if user.features().active(features::new_api).await? {
        return servers::v2::index().await;
    }

    servers::v1::index().await
}
```


`bool` や [rich value](#rich-values) など、フラグ関数が返した型付きの結果を取得するには `value` を使います。

```rust
match user.features().value(features::purchase_button).await? {
    Some(color) => {
        // Show the button in this color...
    }
    None => {
        // Don't show the button...
    }
}
```


Laravel は解決した各値を現在のリクエストが終了するまでメモリにキャッシュします。同じユーザーの同じ機能を複数回チェックしても、ストアへの問い合わせは一度だけです。次のリクエストでは再びストアから読み取ります。

<a name="teams-and-other-scopes"></a>

### Teams and other scopes


チーム全員で使う新しい課金ページなど、機能をチーム全体に適用するには `Team` モデルに `HasFeatures` を実装します。`feature_key` は、Laravel がそのチームの値を保存するための安定した識別子を返します。

```rust
use laravel::feature::{HasFeatures, ScopeKey};

use crate::models::Team;

impl HasFeatures for Team {
    fn feature_key(&self) -> ScopeKey {
        ScopeKey::new("Team", self.id)
    }
}
```


`"Team"` のように短く永続的なスコープ種別を使ってください。種別を変更すると、その型で保存済みの値が参照されなくなります。


チームスコープのフラグ関数は `&Team` を受け取ります。次のフラグは、席数が 50 以上のチームと、それより小さいチームの 1% に新しい課金ページを有効化します。

```rust
use laravel::feature::flag;
use laravel::lottery::Lottery;

use crate::models::Team;

#[flag]
pub fn billing_v2(team: &Team) -> bool {
    team.seats >= 50 || Lottery::odds(1, 100).draw()
}
```


読み込んだ `Team` で機能を直接チェックします。

```rust
if team.features().active(features::billing_v2).await? {
    return Ok(Redirect::to("/billing/v2").into_response());
}
```


各フラグはそのスコープに対応する型を持つため、`User` でチーム向け機能をチェックするとコンパイルに失敗します。

<a name="guests"></a>

### Guests


`&User` を受け取るフラグは、ゲストに対しては関数を実行せず無効と評価します。ゲストも評価する場合は `Option<&User>` を受け取ってください。Laravel はゲストには `None` を渡し、すべてのゲストで一つの保存値を共有します。

```rust
use laravel::feature::flag;

use crate::models::User;

#[flag]
pub fn holiday_banner(user: Option<&User>) -> bool {
    user.is_none_or(|user| !user.is_staff)
}
```


ログインユーザーとゲストの両方がアクセスするハンドラーでは、`Auth<User>` を抽出し、`auth.user()` が返す `Option<User>` に対して直接 `.features()` を呼び出します。`None` の場合、Laravel はゲストとして評価します。

```rust
use laravel::auth::Auth;
use laravel::prelude::*;

use crate::features;
use crate::models::User;

pub async fn home(auth: Auth<User>) -> laravel::Result<Response> {
    let user = auth.user().await?;

    if user.features().active(features::holiday_banner).await? {
        // Show the banner...
    }

    Ok(view("home", ()).into_response())
}
```


`Option<User>` なしでゲストスコープを直接チェック・更新するには、`feature::guest::<User>()` を呼び出します。

<a name="application-wide-features"></a>

### Application-wide features


予定されたメンテナンスのバナーなど、全員で一つの値を使う機能には、スコープ引数のない `#[flag]` 関数を定義します。

```rust
use laravel::feature::flag;

#[flag]
pub fn maintenance_banner() -> bool {
    false
}
```


`laravel::feature` のトップレベル関数で、アプリケーション全体の機能をチェック・更新します。

```rust
use laravel::feature;

if feature::active(features::maintenance_banner).await? {
    // ...
}
```

<a name="middleware"></a>

### Middleware


機能が有効なユーザーだけにルートを制限するには、`RequireFeature` ミドルウェアを付けます。機能が無効な場合、Laravel は `400 Bad Request` を返します。

```rust
use laravel::feature::RequireFeature;
use laravel::prelude::*;

use crate::features;

pub fn routes(route: &mut Router) {
    route
        .get("/api/servers", servers::index)
        .middleware(RequireFeature::new(features::new_api));
}
```


複数の機能を必須にするには、機能ごとに `RequireFeature` を一つずつ付けます。無効時に独自のレスポンスを返すには、ハンドラーを指定して `.otherwise(..)` をチェーンします。

```rust
route
    .get("/servers", servers::index)
    .middleware(
        RequireFeature::new(features::new_api)
            .otherwise(async || Redirect::to("/upgrade")),
    );
```


`RequireFeature` はユーザー機能とアプリケーション全体の機能をサポートします。チームスコープの機能には、チームを解決して `team.features().active(..)` を呼ぶ独自の [middleware](/ja/rust/docs/middleware) を作成してください。

<a name="sharing-features-with-pages"></a>

### Sharing features with pages


フロントエンドでは、UI 要素の表示・非表示に機能フラグをよく使います。`.all()` は、そのスコープ型に定義された全機能を保存名をキーとする JSON オブジェクトで返します。無効なフラグは `false`、複合的な値は JSON にシリアライズされます。

```json
{ "new_api": true, "purchase-button": "seafoam-green", "holiday_banner": false }
```


[Inertia](/ja/rust/docs/inertia) アプリケーションでは、ミドルウェアの [`share`](/ja/rust/docs/inertia#shared-data) メソッドでこのオブジェクトを共有し、全ページが受け取れるようにします。

```rust
// src/http/middleware/handle_inertia_requests.rs
use laravel::inertia::{self, Props, props};
use laravel::prelude::*;

use crate::models::User;

impl inertia::Middleware for HandleInertiaRequests {
    async fn share(&self, request: &Request) -> laravel::Result<Props> {
        let user: Option<User> = request.user().await?;
        let features = user.features().all().await?;

        Ok(props! {
            features => features,
        })
    }
}
```


サーバーレンダリングの [templates](/ja/rust/docs/templates) では、`src/app.rs` の `web` ミドルウェアグループに `ShareFeatures` を追加します。

```rust
use laravel::feature::ShareFeatures;

.with_middleware(|middleware, _| {
    middleware.web(|web| {
        web.append(ShareFeatures::<User>::new());
    });
})
```


これでテンプレートから、フラグの保存名で `feature(name)` を呼べます。未定義のフラグ名を渡すとテンプレートのレンダリングに失敗します。

```jinja
{% if feature("new_api") %}
    <a href="/api/docs">Try the new API</a>
{% endif %}

{% if feature("purchase-button") == "tart-orange" %}
    <button class="bg-orange-500">Buy now</button>
{% endif %}
```

> [!WARNING]
> UI 上のリンクやボタンを隠しても、その先のルートは保護されません。必ずルートのハンドラーで機能をチェックするか、[`RequireFeature`](#middleware) で保護してください。

<a name="eager-loading"></a>

### Eager loading


チーム一覧のようにスコープのリストを描画して各機能をチェックする際、一件ずつ問い合わせるとストアに N+1 の検索が発生します。ループの前に `feature::load` を呼び、全スコープの値を一回のクエリで取得します。

```rust
use laravel::feature;

feature::load(features::billing_v2, &teams).await?;

for team in &teams {
    let billing = team.features().active(features::billing_v2).await?;

    // ...
}
```

<a name="updating-values"></a>

## Updating values


ハンドラー、コマンド、ジョブから、スコープの保存値をプログラムで更新できます。たとえば、顧客に機能への早期アクセスを付与できます。

```rust
use crate::features::{self, ButtonColor};

user.features().activate(features::new_api).await?;

user.features()
    .activate_with(features::purchase_button, ButtonColor::TartOrange)
    .await?;

user.features().deactivate(features::new_api).await?;
user.features().forget(features::purchase_button).await?;
```


真偽値のフラグには `activate`、複合値のフラグには `activate_with` を使います。`forget` は保存行を削除し、次のチェックでフラグ関数を再実行させます。アプリケーション全体の機能には、`feature::deactivate(features::maintenance_banner).await?` など対応するトップレベル関数を呼びます。

<a name="every-scope-at-once"></a>

### Every scope at once


機能を一般公開する準備ができた場合や実験の勝者が決まった場合は、`feature::everyone()` でそのフラグの全保存エントリーを一度に更新します。

```rust
use laravel::feature;

use crate::features::{self, ButtonColor};

feature::everyone().activate(features::new_api).await?;

feature::everyone()
    .activate_with(features::purchase_button, ButtonColor::SeafoamGreen)
    .await?;
```


`activate`、`activate_with`、`deactivate` は、データベースに保存済みのエントリーだけを変更します。まだチェックしたことのないユーザーは初回にフラグ関数の結果を受け取るため、公開を確定する際には関数も更新してください。`forget` は全保存エントリーを削除し、すべてのスコープで次のチェック時に関数を再評価します。

<a name="purging-features"></a>

### Purging features


`feature:purge` コマンドでストア内の機能行を削除できます。コードにまだ定義されている機能を削除すると、次のチェックで `#[flag]` 関数から再計算されます。削除済みの機能をパージすると、その古い行が整理されます。

```shell
laravel feature:purge new_api purchase-button
```


名前を指定せずに `feature:purge` を実行すると、全保存機能が削除され、定義済みの全フラグが再評価されます。特定の名前を保持するには `--except` を、デプロイ時などにアプリケーションで未定義になったフラグだけを削除するには `--except-defined` を指定します。

```shell
laravel feature:purge --except-defined
```

<a name="flags-by-name"></a>

## Flags by name


管理ダッシュボードや API は、コンパイル時の `#[flag]` 型ではなく文字列としてフラグ名を受け取ります。`feature::find` は保存名からフラグを検索し `AnyFlag` を返します。未定義の場合は `None` です。すべてのチェック・変更メソッドは `AnyFlag` を受け取り、複合値は JSON で渡します。


たとえば、次のハンドラーは `PUT /admin/users/{user}/flags` でユーザーのフラグを更新します。ルートは管理者の [authorization](/ja/rust/docs/authorization) で保護してください。

```rust
use laravel::feature;
use laravel::http::NoContent;
use laravel::prelude::*;

use crate::models::User;

#[laravel::input]
#[validate(anyone)]
pub struct UpdateFlag {
    #[validate(required)]
    name: String,
    value: Option<serde_json::Value>,
}

pub async fn update(
    user: User,
    Valid(input): Valid<UpdateFlag>,
) -> laravel::Result<NoContent> {
    let flag = feature::find(&input.name).or_abort(404)?;

    match input.value {
        Some(value) => user.features().activate_with(flag, value).await?,
        None => user.features().deactivate(flag).await?,
    }

    Ok(NoContent)
}
```


JSON 値は、`ButtonColor::SeafoamGreen` に対する `"seafoam-green"` のように、フラグが期待する型へデシリアライズできなければなりません。不正な JSON 値はストアを変更せず、フラグ名を含む `422` レスポンスを返します。定義済みの全フラグを列挙するには `feature::defined()` を呼びます。

<a name="custom-stores"></a>

## Custom stores


Redis や外部の機能フラグサービスなど、別のバックエンドに永続化するには `laravel::feature::FeatureStore` を実装します。値は機能名とスコープをキーとした JSON 文字列として渡されます。

```rust
use laravel::feature::{FeatureStore, ScopeKey, StoredValues};

pub struct RedisFeatureStore;

impl FeatureStore for RedisFeatureStore {
    async fn get_many(
        &self,
        features: &[&str],
        scopes: &[ScopeKey],
    ) -> laravel::Result<StoredValues> {
        // Read every pair's value in one round trip...
        todo!()
    }

    async fn add(
        &self,
        feature: &str,
        scope: &ScopeKey,
        value: &str,
    ) -> laravel::Result<Option<String>> {
        // Store the value unless the scope has one, returning any existing value...
        todo!()
    }

    async fn set(
        &self,
        feature: &str,
        scope: &ScopeKey,
        value: &str,
    ) -> laravel::Result<()> {
        // Store the value, replacing any earlier one...
        todo!()
    }

    async fn update_all(&self, feature: &str, value: &str) -> laravel::Result<()> {
        // Replace every stored value of the feature...
        todo!()
    }

    async fn forget(&self, feature: &str, scope: &ScopeKey) -> laravel::Result<()> {
        // Delete the scope's value...
        todo!()
    }

    async fn purge(&self, features: &[&str]) -> laravel::Result<()> {
        // Delete every value of these features...
        todo!()
    }

    async fn stored_names(&self) -> laravel::Result<Vec<String>> {
        // Return the name of every feature that has a stored value...
        todo!()
    }
}
```


`add` は、ユニークキー競合を無視する挿入などを使い、チェックと挿入をアトミックに行う必要があります。これにより、並行した初回チェックが一つの値に一致します。リモートの機能フラグサービスを使うストアでは `defined_for` も実装でき、Rust で未宣言のフラグを公開できます。呼び出し側は `user.features().find(name)` で検索できます。


`src/app.rs` の `with_services` 内でカスタムストアを登録し、`FEATURE_STORE=redis` で選択します。

```rust
Application::configure()
    .with_services(|app| {
        app.features()
            .extend("redis", |_app| async { Ok(RedisFeatureStore) });
    })
```


パッケージは [service provider's](/ja/rust/docs/packages#service-providers) の `register` メソッド内で、`app.features().extend(..)` を使ってカスタムストアを登録できます。

<a name="testing"></a>

## Testing


テストはデフォルトで `memory` ストアを使い、それぞれ空のストアを持つ独立したアプリケーションで実行されるため、`features` テーブルは不要です。


`feature::fake` で、テスト終了まで全スコープにわたって機能の値を固定できます。

```rust
use laravel::feature;
use laravel::testing::prelude::*;

use app::features::{self, ButtonColor};

#[laravel::test]
async fn the_new_api_lists_servers(app: Application) {
    feature::fake(features::new_api, true);
    feature::fake(features::purchase_button, Some(ButtonColor::TartOrange));

    app.get("/api/servers").await.assert_ok();
}
```


スコープごとに異なる値を返すには、`&User` などフラグのスコープ引数を受け取るクロージャーを渡して `feature::fake_using` を呼びます。

```rust
feature::fake_using(features::new_api, |user| user.id == 1);
```


[lottery](/ja/rust/docs/lottery#testing) を使う機能では `Lottery::always_win()` や `Lottery::always_lose()` を呼べます。特定のフラグが重要な HTTP テストでは、`Lottery::fix` より `feature::fake` を優先してください。ハンドラー実行前にセッションのガベージコレクションや `ShareFeatures` が固定抽選を消費する可能性があるためです。