Search code examples
phplaravelmiddleware

Laravel exclude route in nested Middleware group


I have (schematically) the following situation:

MiddlewareGroup1{

    MiddlewareGroup2{

        Route::resource(...);
        ...
        Route::post('some-ajax-request', 'SomeController@action');

    }

    OtherNestedMiddlewareGroups{
        ...
    }

}

I have the problem that I want MiddlewareGroup2 to apply for the ajax route, but not MiddlewareGroup1. How can I make MiddlewareGroup1 not apply, but keep MiddlewareGroup2?


Solution

  • I guess there is not built in solution here. You can put this route outside MiddlewareGroup1 or you could check current request url in MiddlewareGroup1, like:

    ....
    if ($request->is('some-ajax-request')) {
        return $next($request);
    }
    ....
    

    This will skip MiddlewareGroup1 middleware for defined URL(s).

    If you have many similar ajax routes, you could use similar URLs for them ('ajax-add-stuff', 'ajax-do-some-stuff' etc) and check them like this:

    if ($request->is('ajax*')) { .... }