Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

Subscribe to the newsletter

Get new articles and course lessons delivered to your inbox. No spam, unsubscribe anytime.

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 54 of the Intermediate Laravel: Real-World Application Patterns course
LaravelJune 27, 20263 min read

Using Middleware for Feature Flags in Laravel

Learn how to implement feature flags in Laravel using custom middleware. Gate new functionality safely, manage configuration, and decouple deployment from release.

LaravelMiddlewareFeature FlagsDeploymentArchitecturephpbackend

Previously in this course, we explored implementing middleware for API security. We focused on request authorization, but today we’re shifting our focus to controlling application behavior itself. In this lesson, we’ll implement a feature toggle system that allows you to gate specific routes or features behind configuration settings, enabling you to decouple your deployment from your code's availability.

Why Feature Flags Matter

In a production environment, you rarely want to deploy code that is immediately accessible to everyone. Whether you are running an A/B test or rolling out a complex dashboard migration, you need a way to turn features on or off without touching your deployment pipeline.

Feature flags (or toggles) allow you to ship unfinished or experimental code to production, keeping it dormant until you are ready to flip the switch. By using middleware, we can enforce these gates at the HTTP layer, ensuring unauthorized users never even trigger the logic for a hidden feature.

Implementing a Feature Toggle System

We will create a EnsureFeatureEnabled middleware. This middleware will check our config/features.php file to see if a specific feature key is set to true.

First, create the configuration file:

PHP
#6A9955">// config/features.php
return [
    'beta_dashboard' => env('FEATURE_BETA_DASHBOARD', false),
    'api_v2_access' => env('FEATURE_API_V2', false),
];

Now, generate the middleware:

Bash
php artisan make:middleware EnsureFeatureEnabled

The Middleware Logic

Your middleware needs to accept the feature name as a parameter from the route definition. If the feature is disabled, we will return a 404 Not Found or a custom response.

PHP
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureFeatureEnabled
{
    public function handle(Request $request, Closure $next, string $feature): Response
    {
        if (!config("features.{$feature}", false)) {
            abort(404, 'This feature is currently unavailable.');
        }

        return $next($request);
    }
}

Registering and Using the Middleware

Register your middleware in bootstrap/app.php (or app/Http/Kernel.php if using older Laravel versions):

PHP
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'feature' => \App\Http\Middleware\EnsureFeatureEnabled::class,
    ]);
})

Now, apply it to your routes in routes/api.php:

PHP
Route::middleware(['auth:sanctum', 'feature:beta_dashboard'])->group(function () {
    Route::get('/beta/stats', [DashboardController::class, 'betaStats']);
});

Hands-on Exercise

  1. Define a new flag: Add new_reporting_tool to your config/features.php.
  2. Protect a route: Apply the feature:new_reporting_tool middleware to a new API endpoint.
  3. Toggle it: Change your .env file to FEATURE_NEW_REPORTING_TOOL=true and verify the endpoint responds; then set it to false and confirm it returns a 404.

Common Pitfalls

  • Configuration Caching: If you run php artisan config:cache in production, you must clear the cache (php artisan config:clear) after changing your .env flags, or your changes won't take effect.
  • Naming Collisions: Keep your feature flags namespaced in your config file to avoid collisions with other packages.
  • Stale Flags: Feature flags are technical debt. Once a feature is permanently released, remove the flag and the associated middleware calls. I recommend creating a ticket in your project board to "Remove Flag X" immediately after a successful rollout.

Recap

We’ve successfully decoupled our deployment from our feature releases. By using middleware, we’ve created a clean, readable way to gate code paths. This approach is far superior to cluttering your controllers with if (config(...)) checks, as it keeps your business logic controllers focused on their primary domain—a theme we've emphasized since we started architecting for maintainability.

As you scale this further, you might consider externalizing these flags to a service if you need to toggle features in real-time without modifying environment variables, similar to how we handle deploying Laravel applications with zero downtime.

Up next: We will dive into Job Chaining and Batching, moving from simple background tasks to complex, multi-step workflows.

Previous lessonRefactoring Legacy CodeNext lesson Building Reusable Packages
Back to Blog

Similar Posts

LaravelJune 28, 20263 min read

Handling Webhooks Securely: Validation and Queueing in Laravel

Learn to build production-ready integrations by validating webhook signatures and offloading processing to queues to ensure security and system reliability.

Read more
LaravelJune 28, 20264 min read

Advanced Database Migration Strategies for Laravel

Master non-breaking migrations and safe rollback procedures. Learn the expand-and-contract pattern to evolve your database schema without production downtime.

Part of the course

Intermediate Laravel: Real-World Application Patterns

intermediate · Lesson 54 of 58

  1. 1

    Architecting for Maintainability

    3 min
  2. 2

    Implementing the Service Layer

    3 min
  3. 3

    Repository Pattern Fundamentals

    3 min
Read more
LaravelJune 28, 20264 min read

Advanced API Versioning Strategies: Header-Based Routing in Laravel

Master API versioning and maintain backward compatibility in your distributed systems. Learn to implement header-based versioning for clean, scalable APIs.

Read more
  • 4

    Project Board Domain Modeling

    3 min
  • 5

    Advanced Eloquent Scopes and Accessors

    4 min
  • 6

    Service-Oriented Task Management

    3 min
  • 7

    REST API Fundamentals with Sanctum

    3 min
  • 8

    Resource Controllers and API Responses

    3 min
  • 9

    Handling API Validation and Form Requests

    3 min
  • 10

    Implementing Middleware for API Security

    4 min
  • 11

    Database Transactions for Data Integrity

    3 min
  • 12

    Error Handling and Global Exceptions

    3 min
  • 13

    Introduction to Laravel Events and Listeners

    3 min
  • 14

    Asynchronous Processing with Queues

    4 min
  • 15

    Job Chaining and Batching

    3 min
  • 16

    Feature Testing Fundamentals

    4 min
  • 17

    Mocking Services and Repositories in Tests

    3 min
  • 18

    Testing Events and Jobs

    3 min
  • 19

    Database Factories and Seeding

    3 min
  • 20

    API Versioning Strategies

    4 min
  • 21

    Advanced Request Filtering and Sorting

    3 min
  • 22

    Handling File Uploads in REST APIs

    3 min
  • 23

    Real-time Notifications with Broadcasting

    3 min
  • 24

    Using Observers for Model Lifecycle Hooks

    3 min
  • 25

    Implementing Policies for Authorization

    3 min
  • 26

    Customizing Authentication Guards

    3 min
  • 27

    Rate Limiting API Endpoints

    4 min
  • 28

    Eloquent Performance Optimization

    4 min
  • 29

    Caching Strategies for Performance

    4 min
  • 30

    Using Traits for Code Reuse

    3 min
  • 31

    Advanced Dependency Injection with Service Providers

    3 min
  • 32

    Command Line Tools with Artisan

    3 min
  • 33

    Scheduled Tasks and Cron Jobs

    3 min
  • 34

    Integrating Third-Party Services

    3 min
  • 35

    Handling Webhooks

    3 min
  • 36

    Logging and Monitoring

    3 min
  • 37

    Database Migrations Best Practices

    3 min
  • 38

    Advanced Testing: Integration Tests

    4 min
  • 39

    Testing API Authentication

    4 min
  • 40

    Code Quality and Static Analysis

    3 min
  • 41

    Project Structure for Large Applications

    3 min
  • 42

    Environment and Configuration Management

    3 min
  • 43

    Deploying Laravel Applications

    4 min
  • 44

    Database Indexing Strategies

    4 min
  • 45

    Using Value Objects

    4 min
  • 46

    Strategy Pattern for Business Rules

    3 min
  • 47

    Advanced Queue Monitoring

    3 min
  • 48

    Building a Search API

    3 min
  • 49

    Handling Concurrency and Race Conditions

    4 min
  • 50

    API Documentation with OpenAPI

    3 min
  • 51

    Testing with Test Doubles

    3 min
  • 52

    Implementing Multi-Tenancy

    4 min
  • 53

    Refactoring Legacy Code

    4 min
  • 54

    Using Middleware for Feature Flags

    3 min
  • 55

    Building Reusable Packages

    4 min
  • 56

    Performance Profiling

    3 min
  • 57

    Secure API Design

    3 min
  • 58

    Event Sourcing Concepts

    4 min
  • View full course