Norway


The last few versions of have showed the way works shifting around a bit. This is usually a sign that we’re feeling some sort of pain—something feels off—but haven’t found the perfect solution yet. In 5.3, we may have found it.

Looking back: Routing changes in 5.2

In Laravel 5.2 we temporarily saw two separate route groups in routes.php, one for “” and one for “API”, but that went away mid-5.2.

What stuck around, though, was the idea of multiple middleware groups, and out of the there’s one for “web” routes and one for “API” routes.

The “web” group gets everything you’d expect your normal web users to need: sessions, cookies, CSRF protection, etc. The “API” group is lighter, and came by default with the “throttle” middleware, making the case for a stateless API.

Routing changes in 5.3

In 5.3, the /Http/routes.php file has now moved to the root routes/ directory, and it’s now split into two files: web.php and api.php. As you can probably guess, the routes in routes/web.php are wrapped with the web middleware group and the routes in routes/api.php are wrapped with the api middleware group.

There are a few benefits of this. First, we get the suggestion and easy implementation of the distinction between our web routes and our API routes. Second, it’s now an application-level convention to have multiple routes files, which will likely free more developers up to feel comfortable organizing their routes file this way. And third, this moves the routes directory out of app/, which both makes the routes directory more accessible to new users and makes app/ a fully PSR-4-autoloaded directory, which feels just a bit pure-r.

If you want to customize this or add your own separate routes files, check out AppProvidersRouteServiceProvider for inspiration:

...
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    protected function mapApiRoutes()
    {
        Route::group([
            'middleware' => ['api', 'auth:api'],
            'namespace' => $this->namespace,
            'prefix' => 'api',
        ], function ($router) {
            require base_path('routes/api.php');
        });
    }

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

As you can see, there’s an easy syntax for wrapping the results of any given routes file with a route group and then applying whatever prefixes or middleware or whatever else that you’d like.

That’s it! Enjoy!



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here