Reputation: 7351
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?
Upvotes: 4
Views: 4012
Reputation: 5855
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');
});
Upvotes: 3
Reputation: 6438
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'];
});
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
Upvotes: 2