在 Laravel 的另一个中间件中启用中间件

问题描述 投票:0回答:1

我想知道如何将一个中间件包含在另一个中间件中,例如:

class EnableParamIfExists
{
    public function handle(Request $request, Closure $next)
    {
        $param= $request->input('param1');
        if (!empty($param)) {
            // enable another middleware somthing
            // $another = new AnotherMiddleware();
            // $another->handle(Request $request, Closure $next);
        }
        return $next($request);
    }
}
laravel middleware
1个回答
0
投票

以下是如何有条件地在另一个中间件中应用中间件的示例:

class EnableParamIfExists
{
    public function handle(Request $request, Closure $next)
    {
        $param = $request->input('param1');
        
        if (!empty($param)) {
            // Apply AnotherMiddleware conditionally
            if (/* some condition */) {
                return app(AnotherMiddleware::class)->handle($request, $next);
            }
        }
        
        return $next($request);
    }
}

在此示例中,您根据特定条件有条件地在

AnotherMiddleware
内应用
EnableParamIfExists
。如果满足条件,您可以使用 Laravel 的
app()
函数来解析
AnotherMiddleware
的实例并调用其
handle
方法。

请记住在文件开头导入必要的类:

use Closure;
use Illuminate\Http\Request;
use App\Http\Middleware\AnotherMiddleware;

但是,请记住,这种方法可能会使您的中间件逻辑更加复杂且难以维护。与像这样嵌套中间件不同,将关注点分离到各个中间件中并将它们直接应用到您的路由或路由组可能是更好的做法。这有助于保持代码的清晰度和可读性。

© www.soinside.com 2019 - 2024. All rights reserved.