• Stars
    star
    174
  • Rank 219,104 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 3 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

I recommend using laravel/pennant for any future Feature Flag needs. This package will be frozen as is with no updates planned.

Laravel Feature Flags

Software License PHP Version Run Tests Latest Version on Packagist Total Downloads

I recommend using laravel/pennant for any future Feature Flag needs. This package will be frozen as is with no updates planned.

A simple to use Feature Flag package for Laravel, allowing you to create Feature Groups and assign Users to them - while also being able to give users override access to given features outside of their groups.

Installation

You can install the package via composer:

composer require juststeveking/laravel-feature-flags

You can publish the migrations files with:

php artisan vendor:publish --provider="JustSteveKing\Laravel\FeatureFlags\FeatureFlagsServiceProvider" --tag="migrations"

You can publish the config file with:

php artisan vendor:publish --provider="JustSteveKing\Laravel\FeatureFlags\FeatureFlagsServiceProvider" --tag="config"

This is the contents of the published config file:

return [
    'middleware' => [
        'mode' => 'abort',

        'redirect_route' => '/',

        'status_code' => 404,
    ],
    
    'enable_time_bombs' => false,
    
    'time_bomb_environments' => ['production']
];

You will then need to migrate the database changes:

php artisan migrate

Usage

This package allows you to manage user features and feature groups in a database.

All Feature and Feature Group names will be normalised to lower case on save.

To use this package your User model needs to have the HasFeatures trait:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use JustSteveKing\Laravel\FeatureFlags\Concerns\HasFeatures;

class User extends Authenticatable
{
    use HasFeatures;
}

This will allow you to manage features and feature groups on your user model.

A User can belong to many Feature Groups, but can also be assigned access to specific Features.

Working with Feature Groups

// This will create the Feature Group if not already created and attach the user to it.
auth()->user()->addToGroup('beta testers');

// Alternatively you can use the following syntax
auth()->user()->joinGroup('beta testers');

// You can check if a user is a member of a feature group
auth()->user()->inGroup('beta testers');

// You can also get a user to leave a feature group
auth()->user()->leaveGroup('beta testers');

// You can also pass in more than one group name
auth()->user()->joinGroup('beta testers', 'api testers');

Working with Features

// This will create the Feature if not already created and attach the user to it.
auth()->user()->giveFeature('run reports');

// You can check if a user has a specific feature
auth()->user()->hasFeature('run reports');

// You can also remove a feature for a user
auth()->user()->removeFeature('run reports');

// Like with Feature Groups you can pass in more than one option
// These will return if any are matched.
auth()->user()->hasFeature('run reports', 'admin');

Putting it together

To use the package as a whole:

// Create a Feature Group
$group = FeatureGroup::create([
    'name' => 'Beta Testers'
]);

// Create a Feature
$feature = Feature::create([
    'name' => 'API Access'
]);

// Add the Feature to the Feature Group
$group->addFeature($feature);

// Assign a User to the Group
auth()->user()->joinGroup($group->name);

if (auth()->user()->groupHasFeature('api access')) {
    // The user belongs to a group that has access to this feature.
}

if (auth()->user()->hasFeature('run reports')) {
    // The user has been given access to this feature outside of group features
}

if (auth()->user()->hasFeature('user level feature')) {
    // The user has access to this feature as a user or through a group.
}

Timebombs for Features

A common use case for Feature Flags is to allow developers to add new functionality without breaking existing code.

This process is great when paired with a solid CI/CD pipeline. But the biggest drawback to this is residual technical debt that can occur when developers forget about removing implemented flags across a code base.

To handle this, users of this package can utilise Timebombs! Timebombs are used to cause Feature Flags to throw an exception when a flag should have been removed from the code base.

To use Timebombs, you will need to explicitly enable them within the config ('enable_time_bombs' => true). And define which environments you do not want exceptions to be thrown. (This is particularly useful with CI/CD, as you will want to throw exceptions locally, in CI and on staging environments but NOT on production).

Defining when a timebomb should throw an exception

Once Timebombs are enabled, when creating a new Flag, you will be asked when you want your flag to expire (This is number of days). When the current time surpasses that expiration date, then your feature flag will throw an exception.

To extend a flag, you can use the handy command

php artisan feature-flags:extend-feature

Where you will be prompted to define how many more days are required before the flag should throw an exception again.

Further reading

To learn more on Feature flags and Timebombs, there is a great article by Martin Fowler Here.

Template Usage

There are some Blade Directives to help control access to features in your UI:

// You can check if a user has a specific feature
@feature('api access')
    <x-api-console />
@endfeature

// You can check if a user is a member of a feature group
@featuregroup('beta testers')
    <x-group-feature />
@endfeaturegroup

// You can check if a user is a member of a group with access to a feature
@groupfeature('api access')
    <x-api-console />
@endgroupfeature

Middleware

There are some middleware classes that you can use:

By default you can use:

  • \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\FeatureMiddleware::class
  • \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\GroupMiddleware::class

There 2 middleware classes will either abort on failure, or redirect. The way these work can be managed in the config file for the package. It allows you to set a mode for the middleware (either abort or redirect) and also allows you to set a redirect_route or status_code.

Then there is also:

  • \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\API\FeatureMiddleware::class
  • \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\API\GroupMiddleware::class

These 2 middleware classes only have the one mode of abort but will ready from your config file for the package to know what status code to return, these classes are made specifically for APIs.

To limit access to users with specific features

Add the following to your app/Http/Kernel.php

protected $routeMiddleware = [
    'feature' => \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\FeatureMiddleware::class,
];

You can pass through more than one feature name, and pass them in a friendlier format or as they are:

Route::middleware(['feature:run-reports,print reports'])->group(/* */);

To limit access to users who are part of a feature group

Add the following to your app/Http/Kernel.php

protected $routeMiddleware = [
    'feature-group' => \JustSteveKing\Laravel\FeatureFlags\Http\Middleware\GroupMiddleware::class,
];

You can pass through more than one feature group name, and pass them in a friendlier format or as they are:

Route::middleware(['feature-group:beta-testers,internal,developer advocates'])->group(/* */);

Artisan Commands

There are a number of artisan commands available for interacting with feature flags.

  feature-flags:activate-feature           Activates a feature
  feature-flags:activate-feature-group     Activates a feature group
  feature-flags:add-feature                Add a new feature
  feature-flags:add-feature-group          Add a new feature group
  feature-flags:add-feature-to-group       Add a feature to a group
  feature-flags:deactivate-feature         Deactivates a feature
  feature-flags:deactivate-feature-group   Deactivates a feature group
  feature-flags:view-feature-groups        View feature groups
  feature-flags:view-features              View features
  feature-flags:view-groups-with-features  View groups with features

Testing

$ composer run test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

More Repositories

1

laravel-transporter

Transporter is a futuristic way to send API requests in PHP. This is an OOP approach to handling API requests.
PHP
457
star
2

php-sdk

A Base library for your PHP SDKs
PHP
206
star
3

laravel-webhooks

A simple webhook implementation for Laravel.
PHP
79
star
4

laravel-redoc

A simple API documentation package for Laravel using OpenAPI and Redoc
PHP
75
star
5

os-process

A PHP Package to work with OS processes in an OOP way.
PHP
73
star
6

LaravelPostcodes

A service wrapper around postcodes.io
PHP
73
star
7

laravel-business-process

Laravel Business Process is a simple and clean way to run business process using a Laravel Pipeline, in a structured and type-safe way.
PHP
66
star
8

laravel-data-object-tools

A set of tools to make working with Data Transfer Objects easier in Laravel
PHP
64
star
9

http-status-code

A simple class to return correct status codes for http responses.
PHP
46
star
10

passwordless-auth

A passwordless auth approach in Laravel using Signed URLs
PHP
41
star
11

shop

Online Shop build in Laravel
PHP
39
star
12

laravel-envoyer-sdk

A simple to use PHP class to work with the Laravel Envoyer API
PHP
36
star
13

laravel-stoplight-elements

A simple API documentation package for Laravel using OpenAPI and Stoplight Elements
PHP
36
star
14

laravel-skeleton

My personal Laravel skeleton application.
PHP
30
star
15

laracon-winter-2022-talk

My talk from Laracon Online WInter 2022
PHP
30
star
16

laravel-api-toolkit

A toolkit for creating APIs in Laravel
PHP
24
star
17

fluent-validation

Fluent Validation is a helper package, that allows you to use sensible defaults for your Laravel validation rules.
PHP
24
star
18

password-generator

Generate random, memorable passwords easily.
PHP
22
star
19

companies-house-laravel

A Laravel wrapper to get companies house information and validate company numbers.
PHP
21
star
20

laravel-erp

A simple to use opinionated ERP package to work with Laravel
PHP
20
star
21

uri-builder

A simple URI builder in PHP that is slightly opinionated
PHP
19
star
22

sdk-tools

A set of tools you can use to help make better SDKs.
PHP
19
star
23

ollama-php

A PHP SDK for interacting with the Ollama API.
PHP
18
star
24

todo-cli

A simple CLI application to work with the Todoist API to quickly check your own todo list
PHP
17
star
25

go-api

A simple Go API following concepts of Domain Driven Design for educational purposes.
Go
16
star
26

launchpad

A helpful Laravel package to help me get started in Laravel projects quicker.
PHP
15
star
27

laravel-nuxt

PHP
14
star
28

phponline.dev

The web application for PHP Online
PHP
13
star
29

laravel-buttondown-email

Manage Newsletters in Laravel, using the buttondown.email API
PHP
12
star
30

laravel-stubs

An opinionated version of the Laravel stubs
PHP
11
star
31

skeleton

The skeleton application for Laravel APIs
PHP
11
star
32

invoice-number

A simple to use PHP Invoice Number Generator.
PHP
10
star
33

laravel-erp-crm

A Laravel ERP Module providing CRM functionality
PHP
9
star
34

config-loader

A simple to use configuration loader for PHP.
PHP
8
star
35

dotfiles-mac

This repo is my ongoing progress for working on my personal dotfiles for my devices.
Shell
8
star
36

http-auth-strategies

A simple PHP package that is used to create different Http Auth Headers
PHP
8
star
37

talk-template

This is a template I use to bootstrap my talks, it has all the main components I need to give a good presentation that is well thought out and designed.
Svelte
8
star
38

laravel-tall-eventsourcing-example

An example of using EventSourcing and the TALL stack at the same time
PHP
7
star
39

converter

A CLI tool to turn JSON and YAML into PHP Data Objects quickly
Go
7
star
40

http-slim

A slim psr compliant http client to provide better interoperability
PHP
7
star
41

eloquent-log-driver

A Laravel Log Driver for Eloquent
PHP
7
star
42

masking-engine

A data masking engine for PHP.
PHP
7
star
43

laravel-otp-auth

A Laravel package to provide a one time password authentication flow.
PHP
6
star
44

forum

This is the repo from my Building a Forum livestreams
PHP
6
star
45

laravel-key-factory

A simple package to generate Eloquent model keys
PHP
6
star
46

castr

The cast application from my stream
PHP
6
star
47

http-helpers

A collection of helpers to use when working with HTTP.
PHP
6
star
48

school-management

An open-source School Management Application built with Laravel and Livewire
PHP
6
star
49

laravel-api-service-tutorial

PHP
6
star
50

laravel-toolkit

A simple toolkit package to help me do what I do with Laravel
PHP
6
star
51

jetstream-typescript-vue

Laravel Jetstream with Typescript Vue and Shadcn-vue
Vue
6
star
52

pulsara

A New Universe of Social Connectivity
PHP
6
star
53

tranquil-stay

The Tranquil Stay Booking System is a specialised web-based platform designed to streamline the reservation process for a single hotel.
PHP
6
star
54

laravel-erp-contracts

A package to use when building modules for the Laravel ERP package
PHP
5
star
55

LaravelCityMapper

PHP
5
star
56

nuxt-demo

A NuxtJS demo using tailwind and best practices
JavaScript
5
star
57

workflow

This package is aimed to be a simplistic PHP workflow package that works in a similar fashion to GitHub Actions.
PHP
5
star
58

crm

A Laravel CRM
PHP
5
star
59

micro

A simple to use boilerplate for Slim PHP, for APIs
PHP
5
star
60

laravel-dub

The official Dub.co Laravel integration.
PHP
5
star
61

micro-core

A collection of core components to be used within the micro boilerplate for slim framework.
PHP
4
star
62

ploi-cli

The (unofficial) Ploi CLI application
PHP
4
star
63

ParameterBag

PHP
4
star
64

gtin-php

A PHP package for validating GTIN codes for use in plain PHP and in Laravel.
PHP
4
star
65

calendar

A calendar application built in Laravel
PHP
4
star
66

Bolt-Medium

A Medium Inspired blogging theme for Bolt CMS
HTML
4
star
67

open-source-training-php

This repo is an open source training plan for developers who are interested in learning PHP and related frameworks.
4
star
68

phponline

A community platform
PHP
4
star
69

webhooks

The simplest way to start sending webhooks in PHP.
PHP
4
star
70

personal-github-actions

This repo contains some personal GitHub Actions that do cool things for me
4
star
71

learn-php

This repo is for an online presentation, that gives a gentle introduction to PHP as a language. This can be used as reference material, and is aimed to be used as is with no other downloads needed.
PHP
4
star
72

lapi

LAPI is a very opinionated Laravel template for building APIs in Laravel
PHP
3
star
73

feature-request-platform

PHP
3
star
74

go-api-problem

A simple struct in GoLang for creating API Problems in your API
Go
3
star
75

cypher-query-builder

PHP
3
star
76

BankPHP

Bank is a small and simple, but powerful, database toolkit.
PHP
3
star
77

aggregator

A news aggregator built with Vue, InertiaJS, Laravel, TailwindCSS. Using Dub.co for short-links
PHP
3
star
78

standup

A Web application for managing stand ups as a team
PHP
3
star
79

lemon-squeezy

An unofficial PHP SDK for working with the LemonSqueezy API
PHP
3
star
80

package-skeleton

A PHP Package Skeleton
3
star
81

docker-compose-slim

A simple and clean Slim setup for running with docker-compose
PHP
3
star
82

api-boilerplate

Blade
3
star
83

common-casts

A PHP package that provides common Data and Value Objects, that are Laravel castable.
PHP
3
star
84

fox

A Slim framework 3 bootstrap that is very foxy indeed
CSS
3
star
85

example-go-api

This is an example Go API from my stream on YouTube https://youtu.be/EnWIg_IZg_8
Go
3
star
86

api-starter

A Laravel starter kit for your next API.
PHP
2
star
87

juststeveking.uk-next

HTML
2
star
88

packagist-api

A dead simple API package for the Packagist API.
PHP
2
star
89

neo4j-http-adapter

PHP
2
star
90

JustSteveKing

My GitHub Profile README
2
star
91

fortify-skeleton

A Laravel skeleton repository that uses Laravel Fortify for authentication and FilamentPHP
PHP
2
star
92

amezmo-cli

A CLI tool for the Amezmo API.
PHP
2
star
93

juststeveking.uk-astro

A personal website built using Astro
Astro
2
star
94

federated-auth-service-example

An example of federated authentication as a service in Laravel
PHP
2
star
95

slack

PHP
2
star
96

laravel-mapbox-api

A Laravel package for working with the mapbox API
Shell
2
star
97

cv-builder

This is the repo for the cv-builder stream series
JavaScript
2
star
98

laravel-service

This is an example repo on how to create small/micro-services in Laravel.
PHP
2
star
99

forge-dashboard

An example repo on how to use Laravel Transporter in a Laravel application.
PHP
2
star
100

phponline.dev-new

JavaScript
2
star