Back to Blog
Feature Flags with Laravel Pennant: Safe Deployments and A/B Testing
Why Feature Flags?
Feature flags decouple deployment from release. You can deploy code to production without enabling it for users, then gradually roll out features to specific segments. This reduces risk and enables experimentation.
Getting Started with Pennant
composer require laravel/pennant
php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider"
php artisan migrate
Defining Features
// app/Features/NewCheckoutFlow.php
class NewCheckoutFlow
{
public function resolve(User $user): bool
{
// Enable for beta testers
if ($user->is_beta_tester) {
return true;
}
// Gradual rollout: 20% of users
return $user->id % 100 < 20;
}
}
Checking Features
// In controllers
if (Feature::active(NewCheckoutFlow::class)) {
return view('checkout.new');
}
return view('checkout.legacy');
// In Blade
@feature('new-checkout-flow')
@else
@endfeature
Percentage Rollouts
class NewDashboard
{
public function resolve(User $user): bool
{
// Use lottery for consistent percentage
return Feature::lottery([
50 => true, // 50% get the feature
50 => false, // 50% don't
]);
}
}
A/B Testing
class CheckoutButtonColor
{
public function resolve(User $user): string
{
return Feature::lottery([
33 => 'blue',
33 => 'green',
34 => 'orange',
]);
}
}
// Usage
$color = Feature::value(CheckoutButtonColor::class);
Scoping to Teams/Organizations
// Check feature for a team
Feature::for($team)->active(NewBillingSystem::class);
// Default scope
Feature::define('new-billing', function (Team $team) {
return $team->plan === 'enterprise';
});
Activating/Deactivating
// Manually activate for specific users
Feature::for($user)->activate(NewCheckoutFlow::class);
// Deactivate
Feature::for($user)->deactivate(NewCheckoutFlow::class);
// Activate for everyone
Feature::activateForEveryone(NewCheckoutFlow::class);
Conclusion
Feature flags transform how you deploy and release software. Start using Pennant for safer deployments and data-driven feature decisions.
Related Articles
Need Help With Your Project?
I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.
Get In Touch