EliyaCohen's avatar

I have "web,api" middleware instead of just "api"

Hi,

I'm having a problem when I want to build an API application. Each time when I try to send a POST request to my API, I get the TokenMismatchException. So I wondered why this is happening to me, because the Token middleware exists only in the web group. so I checked the route:list and I so this result:

https://i.gyazo.com/8ba1d6cc0fcf93514b1c5645f7442087.png

As u can see, I have web,api in each route. why is that?

routes.php

<?php

Route::group(['middleware' => ['web']], function () {
//    Route::auth();
});

Route::group(['middleware' => ['api'], 'prefix' => 'api/v1'], function () {

    Route::group(['prefix'  => 'users'], function () {
        Route::post('register',     ['as' => 'user.register', 'uses' => 'UsersController@postRegister']);
        Route::post('login',        ['as' => 'user.login', 'uses' => 'UsersController@postLogin']);
        Route::get('authenticate',  ['as' => 'user.authenticate', 'uses' => 'UsersController@getAuthenticatedUserFromToken']);
    });

});

Why do I have the web middleware and not only the api middleware?

0 likes
2 replies
jusahah87's avatar
Level 5

This happens because 'web'-middleware runs by default on all routes.

Solution is to edit the Providers/RouteServiceProvider.php files mapWebRoutes-method into following:

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

So basically just tell Laravel not to apply web-middleware to everything.

mstnorris's avatar

You no longer need to use the web middleware within your routes.php file. Laravel applies this by default to all Controllers within the default namespace. Just create your API controllers within a namespace such as API like so:

Route::group(['prefix' => 'api', 'as' => 'api_', 'namespace' => 'API', 'middleware' => ['auth']], function() {
    // your routes in here
});

FYI RouteServiceProvider.php showing that the web middleware is only applied to the current namespace.

    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    protected function mapWebRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    }

Please or to participate in this conversation.