4

In Laravel 5.2 the web middleware is included on all routes by default. However, I would like to disable this middleware for all routes within my Api route group without having to specify in each controller to ignore the web middleware.

I do not wish to remove the middleware all together as this is a hybrid app serving both types of clients and still require the xsrf-checking. Is there a way to ignore or 'except' middleware per route group?

2 Answers 2

3

Since Laravel 7.7 you can use excluded_middleware property eg:

Route::group([
    'prefix' => 'forgot-password',
    'excluded_middleware' => ['auth'],
], function () {
    Route::post('send-email', 'ForgotPasswordController@sendEmail');
    Route::post('save-new-password', 'ForgotPasswordController@saveNewPassword');
});
2

My Approach

You may separate you routes file in another file. Check RouteServiceProvider class. In map method, add another line:

public function map(Router $router)
{
    $this->mapWebRoutes($router);

    // This method will register your routes which doesn't need 'web' middleware 
    $this->mapNoMiddlewareRoutes($router);
}

Then add mapNoMiddlewareRoutes method:

protected function mapNoMiddlewareRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace,
    ], function ($router) {
        require app_path('Http/no_middleware_routes.php');
    });
}

}

Finally, add no_middleware_routes.php file within app/Http folder.

Route::get('/foo', function () {
    return ['foo' => 'bar'];
});

2nd Approach

Based on this article, you can use except attribute.

// app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    'webhook/*'
];

As you can see from the example, you can utilize wildcards for route matching or define each one individually. Internally, this array is ran through $request->is and you can find more details about that in the requests documentation.

Read more at CSRF Protection documentation

2
  • This looks like it would work...I will try this for now, but may look into overriding the route middleware loader to provide an 'except' method which I assumed would already be in there considering it exists in the controller middleware stuff. May 26, 2016 at 18:10
  • 1
    See this laravel-news.com/2015/06/…
    – krisanalfa
    May 26, 2016 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.