Skip to content

Conversation

onursimsek
Copy link

We cannot use parameters in terminable middleware. It gives an error if used.

With this PR we can use parameters with terminable middleware.

@rodrigopedra
Copy link
Contributor

rodrigopedra commented Apr 20, 2025

Workaround:

  1. Register your terminable middleware as a singleton on the container (as suggested in the docs, in case you need the same instance to be kept when terminating)
  2. On the middleware's handle() method, assign any parameters you need on the middleware's terminate() method to instance variables
<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class Sample
{
    private readonly array $params;

    public function handle(Request $request, \Closure $next, ...$params): Response
    {
        // 1. assign the arguments to an instance property
        $this->params = $params;

        return $next($request);
    }

    public function terminate(Request $request, Response $response): void
    {
        // 2. use the arguments when terminating 
        Log::info('terminating...', $this->params);

        // IMPORTANT: This class should be registered as a singleton
        // on a Service Provider, so the same instance is retrieved
        // when terminating 
    }
}

@taylorotwell
Copy link
Member

See above workaround.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants