Search code examples
phplaravellaravel-5conditional-statementsmiddleware

Run a middleware on condition - Laravel


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?


Solution

  • 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);
    }