Laravel Feature Flags allows instant, zero-deployment toggling of application features.

Overview

Dynamic Feature Flags for Laravel

Latest Version on Packagist Test Total Downloads

Laravel Feature Flags allows instant, zero-deployment toggling of application features.

The state of each feature flag can be checked from anywhere in the application code (including via a @feature('name') blade directive) to determine whether the conditions you set have been met to enable the feature.

Each feature can be in one of three states:

  • On: enabled for everyone
  • Off: disabled for everyone
  • Dynamic: evaluated according to a feature-specific closure (with a fallback option)

Installation

Install With Composer

composer require codinglabsau/laravel-feature-flags

Database Migrations

php artisan vendor:publish --tag="feature-flags-migrations"
php artisan migrate

Publish Configuration

php artisan vendor:publish --tag="feature-flags-config"

Set Your Cache Store

This package caches the state of features to reduce redundant database queries. The cache is expired whenever the feature state changes.

By default, this package will use the default cache configured in your application.

If you wish to change to a different cache driver, update your .env:

FEATURES_CACHE_STORE=file

Usage

Create a new feature in the database and set the initial state:

use Codinglabs\FeatureFlags\Models\Feature;
use Codinglabs\FeatureFlags\Enums\FeatureState;

Feature::create([
    'name' => 'search-v2',
    'state' => FeatureState::on()
]);

Its recommended that you seed the features to your database before a new deployment or as soon as possible after a deployment.

Check If A Feature Is Enabled

Blade View

Use the @feature blade directive anywhere in your view files.

@feature('search-v2')
    // new search goes here
@else
    // legacy search here
@endfeature

In Your Code

Use the FeatureFlag facade to conveniently check the state of a feature in your app code.

use Codinglabs\FeatureFlags\Facades\FeatureFlag;

if (FeatureFlag::isOn('search-v2')) {
    // new feature code
} else {
    // old code
}

Middleware

Register feature as a route middleware in your HTTP Kernel to protect routes. A 404 response will be returned if the feature does not resolve to the on state.

// app/Http/Kernel.php
protected $routeMiddleware = [
    // ... 
    'feature' => \Codinglabs\FeatureFlags\Middleware\VerifyFeatureIsOn::class,
];

// routes/web.php
Route::get('search-v2', \App\Http\Controllers\SearchV2Controller::class)->middleware('feature:search-v2');

Check If A Feature Is Disabled

Blade View

@unlessfeature('search-v2')
    // no new features for you
@endfeature

In Your Code

use Codinglabs\FeatureFlags\Facades\FeatureFlag;

if (FeatureFlag::isOff('search-v2')) {
    // no new features for you
}

Get The Underlying Current State

If you want to know what the underlying FeatureState value is:

use Codinglabs\FeatureFlags\Facades\FeatureFlag;

// value from Codinglabs\FeatureFlags\Enums\FeatureState
$featureState = FeatureFlag::getState('search-v2');

Updating Feature State

To change the state of a feature you can call the following methods:

use Codinglabs\FeatureFlags\Facades\FeatureFlag;

FeatureFlag::turnOn('search-v2');
FeatureFlag::turnOff('search-v2');
FeatureFlag::makeDynamic('search-v2');

Alternatively you can set the state directly by passing a feature state enum:

FeatureFlag::updateFeatureState('search-v2', FeatureState::on())

It is recommended that you only update a features state using the above methods as it will take care of flushing the cache and dispatching the feature updated event:

\Codinglabs\FeatureFlags\Events\FeatureUpdatedEvent::class

You should listen for the FeatureUpdatedEvent event if you have any downstream implications when a feature state is updated, such as invalidating any cached items that are referenced in dynamic handlers.


Advanced Usage

Dynamic Features

A dynamic handler can be defined in the boot() method of your AppServiceProvider:

use Codinglabs\FeatureFlags\Facades\FeatureFlag;

FeatureFlag::registerDynamicHandler('search-v2', function ($feature, $request) {
    return $request->user() && $request->user()->hasRole('Tester');
});

Dynamic handlers will only be called when a feature is in the dynamic state. This will allow you to define custom rules around whether that feature is enabled like in the example above where the user can only access the feature if they have a tester role.

Each handler is provided with the features name and current request as arguments and must return a boolean value.

Default Handler For Dynamic Features

You may also define a default handler which will be the catch-all handler for features that don't have an explicit handler defined for them:

FeatureFlag::registerDefaultDynamicHandler(function ($feature, $request) {
    return $request->user() && $request->user()->hasRole('Tester');
});

An explicit handler defined using registerDynamicHandler() will take precedence over the default handler. If neither a default nor explicit handler has been defined then the feature will resolve to off by default.

Handle Missing Features

Features must exist in the database otherwise a MissingFeatureException will be thrown. This behaviour can be turned off by explicitly handling cases where a feature doesn't exist:

FeatureFlag::handleMissingFeaturesWith(function ($feature) {
    // log or report this somewhere...
})

If a handler for missing features has been defined then an exception will not be thrown and the feature will resolve to off.

Using Your Own Model

To use your own model, update the config and replace the existing reference with your own model:

// app/config/feature-flags.php

'feature_model' => \App\Models\Feature::class,

Make sure to also cast the state column to a feature state enum using the FeatureStateCast:

// app/Models/Feature.php

use Codinglabs\FeatureFlags\Casts\FeatureStateCast;

protected $casts = [
    'state' => FeatureStateCast::class
];

Sharing features with UI (Inertiajs example)

// app/Middleware/HandleInertiaRequest.php

use Codinglabs\FeatureFlags\FeatureFlags;
use Codinglabs\FeatureFlags\Models\Feature;

Inertia::share([
    'features' => function () {
        return Feature::all()
            ->filter(fn ($feature) => FeatureFlags::isOn($feature['name']))
            ->pluck('name');
    }
]);
// app.js

Vue.mixin({
  methods: {
    hasFeature: function(feature) {
      return this.$page.features.includes(feature)
    }
  }
})
<!-- SomeComponent.vue -->

<div v-if="hasFeature('search-v2')">Some cool new feature</div>

Testing

composer test

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
A package built for lumen that ports most of the make commands from laravel.

A package built for lumen that ports most of the make commands from laravel. For lumen v5.1, but will most likely work for 5.2 as well. I haven't tested. If you have requests, let me know, or do it yourself and make a pull request

Backup your laravel database by a simple artisan command

Backup your laravel database by a simple artisan command This package will allow you to backup your laravel app database and you can also choose to se

Customized loading ⌛ spinner for Laravel Artisan Console.

Laravel Console Spinner Laravel Console Spinner was created by Rahul Dey. It is just a custom Progress Bar inspired by icanhazstring/symfony-console-s

A CLI starter pack for developing a package with Laravel 5

Laravel PackMe Laravel PackMe is a project starter pack which combine all basic stuff (src, tests) in order to develop a package for Laravel 5.*. It t

Extendable Interactive Make Command for Laravel
Extendable Interactive Make Command for Laravel

Extendable Interactive Make Command for Laravel Make your life easier with interactive make command! Installation composer require hydreflab/laravel-m

Laravel Console Toolkit
Laravel Console Toolkit

This Package provides some usefully console features like the attribute syntax for arguments and options, validation, auto ask and casting.

Helper commands for Laravel Beyond Crud

About beyond-crud-helpers This package has many helper commands for the Laravel BEyond CRUD project by Spatie Installation composer require --dev tarr

Instant Upgrades and Instant Refactoring of any PHP 5.3+ code
Instant Upgrades and Instant Refactoring of any PHP 5.3+ code

Rector - Speedup Your PHP Development Rector helps you with 2 areas - major code changes and in daily work. Do you have a legacy code base? Do you wan

A Symfony Feature Flag Bundle which easily allows you to configure and use your favorite feature flag provider.

Metro Markets FF Metro Markets FF is a Feature Flag Symfony Bundle. It easily allows you to configure and use your favorite feature flag provider. Ins

An opinionated feature flags package for Laravel

This package provides an opinionated API for implementing feature flags in your Laravel applications. It supports application-wide features as well as model specific feature flags.

An Unleash bundle for Symfony applications to provide an easy way to use feature flags

Unleash Bundle An Unleash bundle for Symfony applications. This provide an easy way to implement feature flags using Gitlab Feature Flags Feature. Ins

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab.

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab. This implementation conforms to the official Unleash standards and implement

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab. You may also be interested in the Symfony Bundle for this package. This impl

Easily interact and control your feature flags from Filament

Easily interact and control your feature flags from Filament

🚀 Zero-downtime deployment out-of-the-box

🚀 Laravel Deployer Looking for the old Laravel Deployer? Click here. Laravel Deployer is no longer the package it used to be. Since that package was

Nextcloud AIO stands for Nextcloud All In One and provides easy deployment and maintenance with most features included in this one Nextcloud instance.

Nextcloud All In One Beta This is beta software and not production ready. But feel free to use it at your own risk! We expect there to be rough edges

Xero - a digital currency that allows instant payments to anyone, anywhere

Xeros is a digital currency that allows instant payments to anyone, anywhere. Xeros has been written completely in PHP and mostly follows the technical design of Bitcoin. Xeros uses P2P technology to operate with no central server.

🧬 Nano is a zero-config, no skeleton, minimal Hyperf distribution that allows you to quickly build a Hyperf application with just a single PHP file.

Nano is a zero-config, no skeleton, minimal Hyperf distribution that allows you to quickly build a Hyperf application with just a single PHP file.

Best FlexForm based content elements since 2012. With TCA mapping feature, simple backend view and much more features which makes it super easy to create own content element types.
Best FlexForm based content elements since 2012. With TCA mapping feature, simple backend view and much more features which makes it super easy to create own content element types.

DCE-Extension for TYPO3 What is DCE? DCE is an extension for TYPO3 CMS, which creates easily and fast dynamic content elements. Based on Extbase, Flui

Comments
  • St/sc 7287 move syncfeaturesaction over to package with

    St/sc 7287 move syncfeaturesaction over to package with

    • add tests for blade and middleware
    • add SyncFeaturesAction to sync features to database
    • add always_on config item to override state in configured environments
    • add features config item to declare features
    opened by stevethomas 1
  • Improvements

    Improvements

    This PR includes the following changes:

    • Installed cs fixer
    • Updated docs and readme
    • Added GitHub action
    • Installed Spatie enums package
    • Renamed restricted to dynamic
    • Passing tests
    opened by JonathanLouw 0
Releases(v1.3.1)
  • v1.3.1(Aug 30, 2022)

  • v1.3.0(Aug 30, 2022)

    What's Changed

    • St/sc 7287 move syncfeaturesaction over to package with by @stevethomas in https://github.com/codinglabsau/laravel-feature-flags/pull/4
    • Increase code coverage
    • Add features and always_on flags to config

    Full Changelog: https://github.com/codinglabsau/laravel-feature-flags/compare/v1.2.1...v1.3.0

    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Aug 29, 2022)

    What's Changed

    • add tests for middleware by @stevethomas in https://github.com/codinglabsau/laravel-feature-flags/pull/3

    Full Changelog: https://github.com/codinglabsau/laravel-feature-flags/compare/v1.2.0...v1.2.1

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jun 13, 2022)

    Added

    • VerifyFeatureIsOn middleware that returns a 404 if the feature is not on

    Full Changelog: https://github.com/codinglabsau/laravel-feature-flags/compare/v1.1.1...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Jun 13, 2022)

  • v1.1.0(Apr 6, 2022)

  • v1.0.0(Mar 31, 2022)

Owner
Coding Labs
Coding Labs
Generic PHP command line flags parse library

PHP Flag Generic PHP command line flags parse library Features Generic CLI options and arguments parser. Support set value data type(int,string,bool,a

PHP Toolkit 23 Nov 13, 2022
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

Snicco 5 Oct 7, 2022
A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

CLIFramework CLIFramework is a command-line application framework, for building flexiable, simple command-line applications. Commands and Subcommands

Yo-An Lin 428 Dec 13, 2022
PHP CLI tool which allows publishing zipped MODX extra to modstore.pro marketplace

MODX Extra Publisher PHP CLI tool which allows publishing zipped MODX extra to modstore.pro marketplace. Installation global? local? To install packag

Ivan Klimchuk 3 Aug 6, 2021
A PocketMine-MP plugin which allows the users to edit no permission message of commands

CommandPermissionMessage A PocketMine-MP plugin which allows the users to edit no permission message of commands Have you ever got bored by the red me

cosmicnebula200 3 May 29, 2022
Skeleton for creating a new Command Line Interface application with a minimum of dependencies.

Skeleton for creating a new Command Line Interface application with a minimum of dependencies.

Richard van Laak 1 Jan 17, 2022
Cecil is a CLI application that merges plain text files (written in Markdown), images and Twig templates to generate a static website.

Cecil is a CLI application that merges plain text files (written in Markdown), images and Twig templates to generate a static website.

Cecil 209 Jan 2, 2023
Create a simple todo-list application with the basic PHP programming language implemented in the terminal

PHP-DASAR---simple-todo-list-app-with-terminal create a simple todo-list application with the basic PHP programming language implemented in the termin

Ahmad Wali Alchalidi 2 Sep 7, 2022
Display your Laravel routes in the console, but make it pretty. 😎

Pretty Routes for Laravel Display your Laravel routes in the console, but make it pretty. ?? Installation You can install the package via composer: co

Alex 630 Dec 30, 2022