Organizing the routes in Laravel

By default Laravel provides us 4 routes files. These files are pretty much enough for managing routing system for an application. We can divide the routes in other files as well for managing the routings. First let’s see what the 4 routes are meant to be used for.

api.phpThis is where our api routes belongs.
channels.phpThis is where our broadcasting channel exists.
console.phpThis is where our artisan commands belongs.
web.phpThis files contains our routes for the application.

How do we organize our routes for better maintainability ?

Let’s be frank, of course we can manage the whole routes on our web.php which seems to be the one way to manage all the routes. Using middleware , group, prefix and other routes attributes we can easily manage the routes for an application. But no kidding the more the application get huge the more the routes  will get bigger and unmanageable.

Today we are going to split the web.php in admin.php and frontend.php route files for good. First let’s create admin.php and frontend.php in routes directory.

Secondly, let’s get to the file and register the new routes we’ve just created.

How do we register the routes ?

Let’s add two functions for mapping the routes.

Let’s define the both routes to the map() function in the routeServiceProvider class.

The final result will be like this.

Lastly let’s test the routes files. Create FrontendController and AdminController files with index function where we add the below code on both controller.

Now add the route to the routes file.

We have prefixed the admin route with ‘admin’ and frontend route with ‘frontend’. Let’s look at the list of routes.

Hope this tutorials help you organize your routes better and if you do have better option please do share. Happy coding 🙂

Sharing is caring!

Related Post