PHPackages                             turtlemilitia/laravel-featureflags - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. turtlemilitia/laravel-featureflags

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

turtlemilitia/laravel-featureflags
==================================

Laravel package for Turtle Militia feature flag evaluation

v0.2.2(4mo ago)041MITPHPPHP ^8.2CI passing

Since Dec 12Pushed 4mo agoCompare

[ Source](https://github.com/turtlemilitia/laravel-featureflags)[ Packagist](https://packagist.org/packages/turtlemilitia/laravel-featureflags)[ Docs](https://turtlemilitia.com)[ RSS](/packages/turtlemilitia-laravel-featureflags/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (10)Versions (6)Used By (0)

Laravel Feature Flags
=====================

[](#laravel-feature-flags)

A Laravel package for feature flag evaluation with local caching. Designed to work with the [Turtle Militia](https://turtlemilitia.com) feature flags dashboard.

**Requirements:** PHP 8.2+ and Laravel 11 or 12.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Usage](#usage)
- [Targeting Rules](#targeting-rules)
- [Percentage Rollouts](#percentage-rollouts)
- [Experiments](#experiments)
- [Segments](#segments)
- [Webhooks](#webhooks)
- [Fallback Behavior](#fallback-behavior)
- [Conversion Tracking](#conversion-tracking)
- [Error Tracking](#error-tracking)
- [Local Development &amp; Testing](#local-development--testing)
- [Observability](#observability)
- [Performance](#performance)
- [GDPR Compliance](#gdpr-compliance)

Features
--------

[](#features)

- **Local evaluation** - Flags are evaluated locally, no API call per check
- **Smart caching** - Syncs flag configuration and caches locally
- **Targeting rules** - User-based targeting with flexible conditions
- **Percentage rollouts** - Gradual rollouts with sticky bucketing
- **Experiments** - A/B testing with automatic variant assignment
- **Segments** - Reusable user groups
- **Telemetry** - Evaluation tracking sent to dashboard
- **Error tracking** - Correlate errors with feature flags (Sentry, Bugsnag, Flare)
- **Conversion tracking** - Automatic attribution to flag variants
- **Blade directives** - `@feature` directive for templates
- **Auto-context** - Automatically resolves authenticated user context
- **Cache warming** - `featureflags:warm` command for deployments
- **Events** - Optional Laravel events for monitoring
- **GDPR compliant** - Hold telemetry until user consent

Installation
------------

[](#installation)

```
composer require turtlemilitia/laravel-featureflags
```

Quick Start
-----------

[](#quick-start)

Add your API credentials to `.env`:

```
FEATUREFLAGS_API_URL=https://api.turtlemilitia.com/v1
FEATUREFLAGS_API_KEY=your-environment-api-key
```

Check a flag:

```
use FeatureFlags\Facades\Feature;

if (Feature::active('dark-mode')) {
    // Show dark mode UI
}
```

Configuration
-------------

[](#configuration)

Publish the config file to customize settings:

```
php artisan vendor:publish --tag=featureflags-config
```

Most settings work via environment variables:

VariableDescription`FEATUREFLAGS_API_URL`API endpoint`FEATUREFLAGS_API_KEY`Your environment API key`FEATUREFLAGS_WEBHOOK_ENABLED`Enable webhook endpoint`FEATUREFLAGS_WEBHOOK_SECRET`Webhook signature secret`FEATUREFLAGS_TELEMETRY_ENABLED`Send evaluation data to dashboard`FEATUREFLAGS_TELEMETRY_ASYNC`Dispatch telemetry via queue jobs`FEATUREFLAGS_TELEMETRY_QUEUE`Queue name for async telemetry`FEATUREFLAGS_LOCAL_MODE`Use locally-defined flags`FEATUREFLAGS_HOLD_UNTIL_CONSENT`Hold telemetry until user consents`FEATUREFLAGS_CONSENT_TTL_DAYS`Days before consent expires (365)Usage
-----

[](#usage)

```
use FeatureFlags\Facades\Feature;

// Check if a flag is active (boolean)
if (Feature::active('dark-mode')) {
    // Show dark mode UI
}

// Get flag value (supports string, number, JSON)
$limit = Feature::value('api-rate-limit');

// Get all flags
$flags = Feature::all();

// Monitor critical code paths (tracks errors automatically)
$result = Feature::monitor('new-payment-flow', fn ($enabled) =>
    $enabled ? $this->newPayment() : $this->legacyPayment()
);

// Track conversions for A/B analysis
Feature::trackConversion('purchase', $user, ['revenue' => 99.99]);
```

In Blade templates:

```
@feature('new-dashboard')

@else

@endfeature

@feature('premium-feature', $team)
    ...
@endfeature
```

### Context

[](#context)

Context is resolved automatically from the authenticated user. Implement `HasFeatureFlagContext` on your User model:

```
use FeatureFlags\Contracts\HasFeatureFlagContext;

class User extends Authenticatable implements HasFeatureFlagContext
{
    public function toFeatureFlagContext(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'plan' => $this->subscription?->plan,
        ];
    }
}
```

Any model can implement the interface and be passed as context:

```
// Team, Organization, etc.
Feature::active('premium-feature', $team);
```

You can also pass context explicitly:

```
// Array shorthand
Feature::active('new-checkout', [
    'id' => 'user-123',
    'plan' => 'pro',
]);

// Context object
$context = new Context('user-123', ['plan' => 'pro']);
Feature::active('new-checkout', $context);
```

### Nested Traits

[](#nested-traits)

Context supports nested arrays with dot notation in targeting rules. This is useful for targeting based on relationships:

```
public function toFeatureFlagContext(): array
{
    return [
        'id' => $this->id,
        'subscription' => [
            'plan' => [
                'name' => $this->subscription?->plan?->name,
                'tier' => $this->subscription?->plan?->tier,
            ],
            'status' => $this->subscription?->status,
        ],
    ];
}
```

Then target with dot notation in your rules: `subscription.plan.name equals "pro"` or `subscription.status equals "active"`.

Targeting Rules
---------------

[](#targeting-rules)

The dashboard supports these operators for targeting rules:

OperatorDescriptionExample`equals`Exact match`plan equals "pro"``not_equals`Not equal`plan not_equals "free"``contains`String contains`email contains "@company.com"``not_contains`String does not contain`email not_contains "test"``gt`Greater than`age gt 18``gte`Greater than or equal`orders gte 10``lt`Less than`balance lt 100``lte`Less than or equal`balance lte 1000``in`Value in array`country in ["US","GB","CA"]``not_in`Value not in array`country not_in ["CN","RU"]``matches_regex`Regex pattern match`email matches_regex ".*@company\.com$"``semver_gt`Version greater than`app_version semver_gt "2.0.0"``semver_gte`Version greater or equal`app_version semver_gte "2.0.0"``semver_lt`Version less than`app_version semver_lt "3.0.0"``semver_lte`Version less or equal`app_version semver_lte "2.5.0"``before_date`Date is before`created_at before_date "2025-01-01"``after_date`Date is after`trial_end after_date "2025-01-01"``percentage_of`Percentage of attribute values`id percentage_of 50`Example rule (configured in dashboard):

```
{
  "priority": 1,
  "conditions": [
    {
      "trait": "plan",
      "operator": "equals",
      "value": "pro"
    }
  ],
  "value": true
}
```

### Version-Based Targeting

[](#version-based-targeting)

Semver operators are useful when your Laravel app serves as an API backend for mobile apps or versioned frontends. To use them, create a version resolver that provides version traits to the context.

Create a class implementing `ResolvesVersion`:

```
