Mastering Feature Flags with Laravel Pennant
Overview of Feature Management
Deploying new code often feels like a high-stakes gamble. changes this by introducing a lightweight feature flag system. Instead of global releases that impact every user simultaneously, you can isolate new code paths behind toggles. This allows for gradual rollouts, A/B testing, and emergency kill-switches without redeploying your entire application.
Prerequisites
To follow this guide, you should be comfortable with and the framework. Specifically, you need to understand Service Providers, Controllers, and how to interact with Eloquent models. Ensure you have installed via Composer and the migrations executed to create the necessary storage tables.
Defining and Checking Features
Features are typically defined within the boot method of a Service Provider using the Feature::define method.
use Laravel\Pennant\Feature;
use App\Models\User;
Feature::define('checkout-new', function (User $user) {
return $user->is_admin;
});
Once defined, you check the status in your controllers or views. This logic keeps your conditional code clean and centralized.
if (Feature::active('checkout-new')) {
return view('checkout.new');
}
return view('checkout.old');
Storing Dynamic Values
Pennant isn't limited to booleans. You can store strings, arrays, or integers as feature values. This is perfect for multivariate testing, such as changing a button color for specific user segments.
Feature::define('button-color', function (User $user) {
return $user->id % 2 === 0 ? 'blue' : 'green';
});
// Retrieve it using the value method
$color = Feature::value('button-color');
Syntax and Persistence
uses a persistent database driver by default. When a feature closure runs, the result is saved for that specific user (the scope). This ensures a consistent experience; a user won't see a feature flip-flop between sessions. If you need to reset these values during development, use the pennant:purge Artisan command.
Tips and Best Practices
Use the Lottery helper for canary releases. For example, Lottery::odds(1, 100) allows you to safely roll out a feature to 1% of your traffic. Always clean up your flags once a feature is 100% rolled out to keep your codebase maintainable and prevent "flag debt."
- 43%· products
- 29%· products
- 14%· products
- 14%· people

Pennant - Release features with confidence
WatchLaravel // 5:04
The official YouTube channel of Laravel, the clean stack for Artisans and agents. We will update you on what's new in the world of Laravel, from the framework to our products Cloud, Forge, and Nightwatch.