Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web middleware being applied to API routes in Laravel 5.2

I have the following routes in place:

Route::group(['prefix' => 'api/v1', 'middleware' => 'api'], function() {
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
    Route::resource('users', 'UserController');
});

The UserController has a test to ensure that when a user is submitted via POST, that it validates the input correctly. This should return a 422 when invalid, but it actually returns a 302. In Postman, it raises a CSRF token error, suggesting the web middleware group is being applied, which is not the behaviour I want.

How can I prevent this happening?

like image 976
Matthew Daly Avatar asked Apr 07 '16 13:04

Matthew Daly


1 Answers

In RouteServiceProvider.php change

    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/routes.php');
    });

to:

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

And then wrap your web routes with Route::group(['middleware' => 'web']) in routes.php. So api routes will be not affected by web middleware.

like image 193
Giedrius Kiršys Avatar answered Oct 27 '22 14:10

Giedrius Kiršys