Warm tip: This article is reproduced from serverfault.com, please click

Run a middleware on condition

发布于 2018-10-11 07:10:57

I have a middleware that checks for a specific header parameter in the request and sends back a response based on that.

But the problem I have is that I don't want this middleware run always on a function in my Controller. I want that middleware runs if a condition gets true in a function (for example: store function).

How can I achieve this?

Questioner
Saman Sattari
Viewed
0
common sense 2018-11-16 01:00:12

Middlewares are called before hitting an controller action. So its not possible to execute a middleware based on a condition inside an action. However, it is possible to conditional execution of middleware:

Via the Request

You can add the condition to the request object (hidden field or similar)

public function handle($request, Closure $next)
{
    // Check if the condition is present and set to true
    if ($request->has('condition') && $request->condition == true)) {
        //
    }

    // if not, call the next middleware
    return $next($request);
}

Via parameter

To pass a parameter to the middleware, you have to set it in the route definition. Define the route and append a : with the value of the condition (in this example a boolean) to the name of the middleware.

routes/web.php

Route::post('route', function () {
//
})->middleware('FooMiddleware:true');

FooMiddleware

public function handle($request, Closure $next, $condition)
{
    // Check if the condition is present and set to true
    if ($condition == true)) {
        //
    }

    // if not, call the next middleware
    return $next($request);
}