Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Stack Middleware Laravel Package

barryvdh/laravel-stack-middleware

Adds a simple stack-style middleware manager for Laravel, letting you group, push, and compose middleware in a defined order. Useful for building reusable request/response pipelines and applying them to routes or controllers with minimal boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require barryvdh/laravel-stack-middleware
    

    No additional configuration is required—it auto-registers with Laravel’s service provider.

  2. First Use Case: Define a middleware stack in app/Http/Kernel.php:

    protected $middlewareStacks = [
        'admin' => [
            \App\Http\Middleware\TrustProxies::class,
            \App\Http\Middleware\CheckForMaintenanceMode::class,
            \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
            \App\Http\Middleware\TrimStrings::class,
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            \App\Http\Middleware\Authenticate::class,
        ],
    ];
    
  3. Apply the Stack: Use the stack in your routes:

    Route::middleware(['stack:admin'])->group(function () {
        Route::get('/dashboard', [DashboardController::class, 'index']);
    });
    

    Or in a controller:

    public function __construct()
    {
        $this->middleware('stack:admin');
    }
    
  4. Verify: Run a test request to ensure the middleware stack executes as expected. Use Laravel’s built-in debugging tools like php artisan route:list or php artisan middleware:list to confirm.


Implementation Patterns

Core Workflows

  1. Defining Stacks:

    • Global Stacks: Define in app/Http/Kernel.php under $middlewareStacks.
    • Dynamic Stacks: Create a service provider to register stacks conditionally:
      public function boot()
      {
          if ($this->app->environment('production')) {
              $this->app['router']->middlewareStacks['prod'] = [
                  \App\Http\Middleware\RateLimit::class,
                  \App\Http\Middleware\ThrottleRequests::class,
              ];
          }
      }
      
  2. Reusing Stacks:

    • Nested Stacks: Reference other stacks within a stack:
      'api' => [
          \App\Http\Middleware\ApiAuthenticate::class,
          'stack:auth', // Reuse the 'auth' stack
      ],
      
    • Conditional Stacks: Use middleware to dynamically switch stacks:
      public function handle($request, Closure $next)
      {
          if ($request->bearerToken()) {
              $stack = 'api';
          } else {
              $stack = 'web';
          }
          return app(\Barryvdh\StackMiddleware\Facades\StackMiddleware::class)
              ->stack($stack)
              ->run($request, $next);
      }
      
  3. Testing:

    • Unit Tests: Mock the middleware stack resolution:
      $stack = \Barryvdh\StackMiddleware\Facades\StackMiddleware::stack('admin');
      $this->assertCount(6, $stack->getMiddleware());
      
    • HTTP Tests: Verify stack behavior in routes:
      $response = $this->actingAs($user)->get('/dashboard');
      $response->assertStatus(200);
      

Integration Tips

  1. Leverage Laravel’s Middleware Groups: Combine with Laravel’s built-in $middlewareGroups for hybrid stacks:

    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        'stack:auth', // Custom stack
        \Illuminate\Session\Middleware\AuthenticateSession::class,
    ],
    
  2. Dynamic Stacks via Facade: Use the facade to build stacks at runtime:

    $stack = \Barryvdh\StackMiddleware\Facades\StackMiddleware::stack('api');
    $stack->push(\App\Http\Middleware\LogIp::class);
    
  3. Environment-Specific Stacks: Define stacks in a config file (e.g., config/middleware.php) and load them in a service provider:

    $this->app['router']->middlewareStacks = config('middleware.stacks');
    
  4. Parallel Middleware Execution: For non-blocking middleware (e.g., logging, analytics), use Laravel’s parallel middleware wrapper:

    'analytics' => [
        \App\Http\Middleware\ParallelMiddleware::class,
        \App\Http\Middleware\LogRequest::class,
        \App\Http\Middleware\TrackAnalytics::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters:

    • Incorrect ordering can break functionality (e.g., auth before CORS). Always validate stack order with tests.
    • Fix: Use php artisan middleware:list to debug execution order.
  2. Circular Dependencies:

    • Avoid referencing the same stack recursively (e.g., stack:auth includes stack:api, which includes stack:auth).
    • Fix: Refactor stacks to avoid circular includes or use a dependency checker.
  3. Stack Not Found Errors:

    • Laravel throws InvalidArgumentException if a stack name is misspelled or undefined.
    • Fix: Validate stack names in tests or use a fallback stack:
      $stack = \Barryvdh\StackMiddleware\Facades\StackMiddleware::stack('undefined', ['fallback.middleware']);
      
  4. Performance Overhead:

    • Overusing dynamic stacks or deeply nested stacks can impact performance.
    • Fix: Profile with Blackfire or Laravel Debugbar and optimize critical paths.
  5. Facade vs. Direct Usage:

    • The facade (StackMiddleware) is convenient but can lead to tight coupling. Prefer dependency injection for complex logic:
      public function __construct(private StackMiddleware $stackMiddleware) {}
      

Debugging Tips

  1. Log Stack Resolution: Add logging to trace stack execution:

    \Barryvdh\StackMiddleware\Facades\StackMiddleware::enableLogging();
    

    Logs appear in storage/logs/laravel.log.

  2. Middleware Debugging: Use php artisan middleware:debug to inspect the middleware pipeline:

    php artisan middleware:debug --route=dashboard
    
  3. Test Stacks in Isolation: Create a dedicated test stack for debugging:

    'debug' => [
        \App\Http\Middleware\LogRequest::class,
        \App\Http\Middleware\ValidateSignature::class,
    ],
    

    Apply it to a test route and inspect logs.

Configuration Quirks

  1. Stack Naming Conventions:

    • Use kebab-case or snake_case for stack names (e.g., api-auth, admin_panel).
    • Avoid reserved Laravel names (e.g., web, api) unless extending them.
  2. Service Provider Registration: If defining stacks dynamically, ensure the service provider boots after StackMiddlewareServiceProvider:

    public function register()
    {
        $this->app->register(\Barryvdh\StackMiddleware\StackMiddlewareServiceProvider::class);
    }
    
  3. Laravel 11/12 Compatibility:

    • The package supports Laravel 11/12, but some middleware (e.g., TrustProxies) may behave differently. Test thoroughly.

Extension Points

  1. Custom Stack Resolvers: Extend the stack resolver to support dynamic logic:

    use Barryvdh\StackMiddleware\StackResolver;
    
    class CustomStackResolver extends StackResolver
    {
        public function resolve($stack)
        {
            if ($stack === 'tenant') {
                return $this->app['tenant.middleware'];
            }
            return parent::resolve($stack);
        }
    }
    

    Bind it in a service provider:

    $this->app->bind(StackResolver::class, CustomStackResolver::class);
    
  2. Middleware Stack Events: Listen for stack-related events (e.g., stack.resolved):

    \Barryvdh\StackMiddleware\Facades\StackMiddleware::listen('stack.resolved', function ($stack) {
        logger()->info("Stack resolved: {$stack->getName()}");
    });
    
  3. Parallel Middleware: For Laravel 11+, use the parallel middleware wrapper to execute non-blocking middleware concurrently:

    'analytics' => [
        \Illuminate\Pipeline\ParallelMiddleware::class,
        \App\Http\Middleware\LogRequest::class,
        \App\Http\Middleware\TrackAnalytics::class,
    ],
    

Pro Tips

  1. Stack Aliases: Create aliases for frequently used stacks in app/Providers/AppServiceProvider.php:

    $this->app->alias('stack.admin', \Barryvdh\StackMiddleware\Facades\StackMiddleware::class . '@stack');
    
  2. Environment-Specific Stacks: Load stacks from environment-specific config files:

    $stacks = require config_path('middleware/' . config('app.env') . '.php');
    $this->app['router']->middlewareStacks = $stacks;
    
  3. Stack Validation: Validate stack definitions in a service provider:

    public function boot()
    {
        $stacks =
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor