发送变量以在中间件中终止

mr *_*per 2 middleware laravel

我正在尝试发送一个变量以从路由终止中间件:

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

我可以获取checkUserLevel中间件的句柄,但我也需要在终止方法中访问,我该怎么办?

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

public function terminate($request, $response)
{
      //I need that variable here
}
Run Code Online (Sandbox Code Playgroud)

Niz*_*diq 5

正如文档中提到的,如果您想使用相同的中间件实例(因为默认情况下它使用新的中间件实例),您需要将中间件注册为单例。

您可以通过添加到您的方法将其注册为ServiceProviderregister

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

然后你可以像洛伦特答案的第一个例子一样使用类的属性

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);
}
Run Code Online (Sandbox Code Playgroud)