Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 810
Saman Sattari Avatar asked Oct 25 '25 17:10

Saman Sattari


1 Answers

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);
}
like image 137
common sense Avatar answered Oct 27 '25 07:10

common sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!