'Send variable to terminate in middleware

I am trying to send a variable to terminate of middleware from route:

Route::group(['middleware' => 'checkUserLevel'], function () {
    // my routes
});

I can get checkUserLevel in handle of middleware but I need to access in terminate method too, what should I do?

public function handle($request, Closure $next, $key)
{
     dd($key); // it returns variable
}

public function terminate($request, $response)
{
      //I need that variable here
}


Solution 1:[1]

As mentioned in documentation, if you would like to use the same instance of middleware (because by default it is using the fresh instance of middleware) you need to register the middleware as singleton.

You can register it as singleton by adding to your ServiceProvider's register method

public function register()
{
    $this->app->singleton(\App\Http\Middleware\YourMiddleware::class);
}

Then you can use the class' property like the first example of lorent's answer

protected $foo;

public function handle($request, Closure $next)
{
    $this->foo = 'bar';

    return $next($request);
}

public function terminate($request, $response)
{
    // because we cannot use `dd` here, so the example is using `logger`
    logger($this->foo);
}

Solution 2:[2]

You can do:

protected $key;

public function handle($request, Closure $next, $key)
{
     $this->key = $key;
}

public function terminate($request, $response)
{
     $this->key; //access property key
}

even though this should be passed via request global. Like:

public function handle($request, Closure $next)
{
     $request->input('key');
}

public function terminate($request, $response)
{
      $request->input('key');
}

Edited:

Route::group(['middleware' => 'checkUserLevel'], function () {
    Route::get('/test/{testparam}', function () {
    });
});

public function handle($request, Closure $next)
{
     $request->route('testparam');
}

public function terminate($request, $response)
{
      $request->route('testparam');
}

Solution 3:[3]

I know this is ages old, but you could also use a static property. That saves you from having to register a singleton:

<?php

namespace App\Http\Middleware;

class MyMiddleware {
    private static $key;

    public function handle($request, Closure $next, $key)
    {
         self::$key = ($key); // it returns variable
    }

    public function terminate($request, $response)
    {
          $key = self::$key;
    }
}

This works in my Laravel 5.8 application, don't see why it wouldnt' work anywhere else. Cannot say if there's any reason NOT to do this, but I don't know of one.

I'm using this myself to generate a Cache key in my handle function, and reuse the same key in my terminate function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jamesking56
Solution 3 TKoL