geckob
geckob

Reputation: 8138

Avoid/remove web middleware in routes for Laravel >= 5.2.31

After this changes which is Laravel 5.2.31 and above, all routes in app/Http/routes.php will fall under web middleware group.

In RouteServiceProvider.php

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

The questions:

  1. What is the easiest/best way to define set of routes without web middleware?

One of the use case for this is, declaring routes for stateless api without session middleware which falls under web group middleware

Upvotes: 3

Views: 4778

Answers (1)

geckob
geckob

Reputation: 8138

One way I solved this is by editing the app/Providers/RouteServiceProvider.php and having another route files for other group middleware ie api

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

    //
}

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

// Add this method and call it in map method. 
protected function mapApiRoutes(Router $router)
{
    $router->group([
        'namespace' => $this->namespace, 'middleware' => 'api',
    ], function ($router) {
        require app_path('Http/routes-api.php');
    });
}

To verify the result, run php artisan route:list on terminal and check the route middleware.

For instance:

Now I have some route without web middleware which is defined in different file which later called in RouteServiceProvider

Now I have some route without web middleware which is defined in different file which later called in RouteServiceProvider

OR

If you prefer the old features, you can have something like this:

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

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

Then, in routes-general.php you can have multiple middleware groups for different set of routes just like before

Upvotes: 7

Related Questions