Feature Flag System in Laravel 11 for Controlled Releases

Websolutionstuff | Oct-09-2024 | Categories : Laravel

Hello, laravel web developers! In this tutorial, I will show you how to build a feature flag system in Laravel 11 that allows you to control the release of new features incrementally. By implementing feature flags, you can enable or disable features for specific users or user groups without the need to redeploy your code.

This approach is perfect for testing new features with a small audience or rolling out changes gradually across your application. Let’s walk through the steps to create a feature flag system with feature toggles, user targeting, and dynamic updates.

Feature Flag System in Laravel 11 for Controlled Releases

Feature Flag System in Laravel 11 for Controlled Releases

 

Step 1: Setting Up the Feature Flag Model and Migration

First, we’ll need a way to store feature flags in the database. Let’s create a FeatureFlag model and corresponding migration

php artisan make:model FeatureFlag -m

In the migration file, define the table structure.

Migration:

public function up()
{
    Schema::create('feature_flags', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->boolean('enabled')->default(false);
        $table->json('targeted_users')->nullable();
        $table->timestamps();
    });
}

This table will store the flag name, whether the feature is enabled, and the list of users (if any) who should have access to the feature.

php artisan migrate

 

Step 2: Seeding Feature Flags

Next, create a seeder to populate your FeatureFlags table with some flags.

php artisan make:seeder FeatureFlagSeeder

In the seeder file, add the following:

database/seeders/FeatureFlagSeeder.php

public function run()
{
    DB::table('feature_flags')->insert([
        ['name' => 'new_dashboard', 'enabled' => false, 'targeted_users' => json_encode([1, 2])],
        ['name' => 'beta_feature', 'enabled' => false, 'targeted_users' => null],
    ]);
}

Run the seeder:

php artisan db:seed --class=FeatureFlagSeeder

 

Step 3: Creating a Feature Flag Service

Let’s create a service that checks whether a feature is enabled or not.

app/Services/FeatureFlagService.php

namespace App\Services;

use App\Models\FeatureFlag;

class FeatureFlagService
{
    public function isFeatureEnabled(string $featureName, $userId = null): bool
    {
        $flag = FeatureFlag::where('name', $featureName)->first();
        
        if (!$flag || !$flag->enabled) {
            return false;
        }

        if ($flag->targeted_users) {
            $targetedUsers = json_decode($flag->targeted_users, true);
            return in_array($userId, $targetedUsers);
        }

        return true;
    }
}

This service will first check if the feature is globally enabled and, if there’s user targeting, whether the feature is available for the given user.

 

Step 4: Updating the Controller to Check Feature Flags

In your controllers, use the FeatureFlagService to control access to specific features.

app/Http/Controllers/DashboardController.php

use App\Services\FeatureFlagService;

public function show(FeatureFlagService $featureFlagService)
{
    $userId = auth()->user()->id;

    if ($featureFlagService->isFeatureEnabled('new_dashboard', $userId)) {
        // Load new dashboard
        return view('dashboard.new');
    } else {
        // Load old dashboard
        return view('dashboard.old');
    }
}

 

Step 5: Dynamic Updates without Redeploying Code

To allow dynamic updates without redeploying, you can manage the feature flags directly in the database. For example, you can create an admin interface that lets you toggle flags or update targeted users in real-time.

You can add a simple admin interface:

routes/web.php

Route::get('/admin/feature-flags', [FeatureFlagController::class, 'index']);
Route::post('/admin/feature-flags/update', [FeatureFlagController::class, 'update']);

app/Http/Controllers/FeatureFlagController.php

use App\Models\FeatureFlag;

public function index()
{
    $flags = FeatureFlag::all();
    return view('admin.feature-flags.index', compact('flags'));
}

public function update(Request $request)
{
    $flag = FeatureFlag::find($request->id);
    $flag->enabled = $request->enabled;
    $flag->targeted_users = json_encode($request->targeted_users);
    $flag->save();

    return redirect()->back()->with('status', 'Feature flag updated!');
}

 


You might also like:

Recommended Post
Featured Post
Comparing VPS Hosting Providers with Global Data Centers
Comparing VPS Hosting Provider...

It can be hard to find the best VPS hosting UAE provider with global data centers in today’s market. The majority...

Read More

Jun-26-2024

Laravel 9 Multiple Authentication Using Middleware
Laravel 9 Multiple Authenticat...

In this article, we will see laravel 9 multiple authentications using middleware. Using middleware we authenticate the u...

Read More

Apr-13-2022

How To Get Last 30 Days Record In Laravel 8
How To Get Last 30 Days Record...

in this tutorial, we see how to get last 30 days record in laravel 8. You can simply get the last 30 days reco...

Read More

Feb-02-2022

Laravel 9 Datatables Filter with Dropdown
Laravel 9 Datatables Filter wi...

In this article, we will see laravel 9 datatables filter with dropdown. Here we will add datatables...

Read More

Mar-12-2022