Understanding Feature Flags in Laravel #
Feature flags, also known as feature toggles, are powerful techniques in modern software development that allow you to turn specific functionalities of your application on or off without deploying new code. This provides immense flexibility for A/B testing, gradual rollouts (dark launches), emergency kill switches, and personalizing user experiences.
Laravel Toggle is a lightweight package designed to bring this essential capability to your Laravel applications with minimal overhead. It enables you to control features globally using environment variables, your database, or a combination of both, offering a robust and simple solution for managing application features.
In this tutorial, we'll walk you through setting up and using Laravel Toggle to implement feature flags in your Laravel project.
Step 1: Installation #
The first step is to install Laravel Toggle via Composer. Open your terminal in your Laravel project's root directory and run:
composer require staudenmeir/laravel-toggle
Step 2: Configuration #
After installation, you'll need to publish the package's configuration file. This allows you to customize its behavior, such as choosing the driver (environment variables or database) and defining default values.
php artisan vendor:publish --provider="Staudenmeir\LaravelToggle\LaravelToggleServiceProvider"
This command will create a toggle.php file in your config directory. Open config/toggle.php to review its contents:
return [
/*
|--------------------------------------------------------------------------
| Default Toggle Driver
|--------------------------------------------------------------------------
|
| This option controls the default toggle driver that will be used.
| Valid options are "env", "database", or "both".
|
*/
'driver' => env('TOGGLE_DRIVER', 'env'), // Default to 'env'
/*
|--------------------------------------------------------------------------
| Toggle Default Value
|--------------------------------------------------------------------------
|
| This value will be returned when a toggle is not found.
|
*/
'default_value' => false,
/*
|--------------------------------------------------------------------------
| Database Table
|--------------------------------------------------------------------------
|
| This is the database table that will be used to store toggles.
|
*/
'table' => 'features',
];
You can change the driver in your .env file, for example: TOGGLE_DRIVER=database or TOGGLE_DRIVER=both.
Step 3: Database Driver Setup (Optional) #
If you choose database or both as your driver, you'll need to create a table to store your feature flags. Laravel Toggle provides a convenient command for this:
php artisan toggle:table
php artisan migrate
This will create a features table in your database with columns like name and active. You can then manage your feature flags directly from this table. For example, to enable a feature named new-dashboard:
INSERT INTO features (name, active, created_at, updated_at) VALUES ('new-dashboard', 1, NOW(), NOW());
Or programmatically:
// In a seeder or controller
\DB::table('features')->insert([
'name' => 'new-dashboard',
'active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
Step 4: Defining and Using Feature Flags #
Now that Laravel Toggle is configured, you can start defining and using feature flags throughout your application.
4.1. Using Environment Variables (Driver: env or both)
The simplest way to define a flag is through your .env file. Prefix your flag name with TOGGLE_.
Example: To create a flag for a "New Dashboard":
TOGGLE_NEW_DASHBOARD=true
TOGGLE_BETA_FEATURES=false
Remember to run php artisan config:clear if your .env changes aren't immediately reflected in cached configurations.
4.2. Accessing Flags in Your Code
Laravel Toggle provides a facade to easily check the status of your flags.
use Staudenmeir\LaravelToggle\Facades\Toggle;
- Checking if a feature is ON:
if (Toggle::on('new-dashboard')) { // Render the new dashboard UI } - Checking if a feature is OFF:
if (Toggle::off('experimental-feature')) { // Hide the experimental feature } - Checking with a default value (if not found in env/db):
Thedefault_valueinconfig/toggle.phpcovers this, but you can also explicitly pass a second argument toon()oroff()to override the default for that specific check.// If 'super-secret-feature' isn't defined anywhere, this will return true if (Toggle::on('super-secret-feature', true)) { // ... }
4.3. Practical Examples
-
In Controllers:
Control logic or pass variables to views based on feature flags.namespace App\Http\Controllers;use App\Http\Controllers\Controller; use Staudenmeir\LaravelToggle\Facades\Toggle;
class DashboardController extends Controller { public function index() { $showNewDashboard = Toggle::on('new-dashboard'); $showBetaFeatures = Toggle::on('beta-features');
return view('dashboard.index', compact('showNewDashboard', 'showBetaFeatures')); }}
-
In Blade Views:
Conditionally display UI elements.Welcome to your Dashboard
@if ($showNewDashboard)
You are viewing the NEW Dashboard experience!{{-- Include the new dashboard component --}}@else You are viewing the CLASSIC Dashboard experience. Try the new one!{{-- Include the old dashboard component --}}@endif @if (Toggle::on('beta-features'))
@endifBeta Features #
Welcome to our exclusive beta features!
{{-- ... other beta content ... --}} -
In Routes (via Middleware):
Restrict access to certain routes based on feature flags.// web.php use Staudenmeir\LaravelToggle\Facades\Toggle;Route::middleware('web')->group(function () { // Public routes Route::get('/', function () { return view('welcome'); });
// Routes requiring 'new-dashboard' feature Route::middleware(function ($request, $next) { if (Toggle::on('new-dashboard')) { return $next($request); } // If the feature is off, redirect or abort return redirect('/old-dashboard')->with('error', 'New dashboard is not active yet.'); })->group(function () { Route::get('/dashboard/new', [App\Http\Controllers\NewDashboardController::class, 'index'])->name('new.dashboard'); }); // Other authenticated routes Route::get('/dashboard/old', [App\Http\Controllers\OldDashboardController::class, 'index'])->name('old.dashboard');});
Benefits and Use Cases of Laravel Toggle #
- Controlled Rollouts: Introduce new features to a small group of users before a full public release.
- A/B Testing: Easily switch between different versions of a feature to test user engagement and performance.
- Emergency Kill Switches: Quickly disable a problematic feature without requiring a code rollback or redeployment.
- Separation of Deployment and Release: Deploy code containing new features that are initially disabled, then activate them when ready.
- Seasonal Features: Turn on/off features for holidays or specific campaigns.
Conclusion #
Laravel Toggle provides a straightforward and efficient way to implement feature flags in your Laravel applications. By leveraging environment variables or the database, you gain significant control over your application's functionalities, allowing for safer deployments, dynamic user experiences, and improved development workflows. Start integrating feature flags today to unlock a new level of agility in your Laravel projects!