Organize your Laravel 11 routes for better and maintainable code

Sourav Rakshit
5 min readDec 14, 2017

--

Right out of the gate, Laravel 11 simplifies its routing system by providing two primary route files: web.php for web routes and console.php for console-based commands. This streamlined approach caters to a wide range of web applications and command-line tasks, ensuring a clear and manageable routing structure from the start.

However, some route files are not present by default anymore, including api.php for APIs (if your app needs REST endpoints) and channels.php for broadcasting purposes.

We all know these things, so far nothing new in that right!

💡 Purpose of This Article:

Managing routes in a small application might seem straightforward, often requiring only the web.phpfile for all routing needs. However, as your application grows to include hundreds of routes catering to different user roles—like admins, customers, or other authenticated users—plus common unprotected routes accessible to all visitors, relying solely on a single route file becomes impractical.

Initially, relying on web.php as the singular routing source may offer simplicity for small projects, yet this simplicity can quickly become a hindrance as your application expands.

⚠️ This necessitates the adoption of more sophisticated and scalable routing solutions to ensure efficient route management.

🧪 Here is a really nice & clean solution to this problem:

A highly effective solution involves categorizing routes into distinct groups based on their access levels or user roles. Assume we have three types of routes and we are dividing them into three main categories:

  1. Admin Level Routes: These are routes intended for administrative users, offering access to backend functionalities.
  2. User Level Routes: Routes for registered users, enabling them to sign up, log in, and manage their profiles, among other actions.
  3. Public Routes: These routes are accessible to everyone, including the home page, blog, and contact page.

This approach not only enhances the clarity and manageability of your routes but also streamlines the process of applying middleware for authentication and authorization across different sections of your application.

Let’s start by creating one web directory inside routes

Laravel 11 routes
modified routes directory in laravel 11

☝ ️ routes/webhere goes all our web interface related routes

Let’s strategically place the default web.php within the web 📁 directory, maintaining its role as the foundation of web interfaces. As for console.php, let it reside in its native habitat, the routes 📁, safeguarding its duty for artisan commands.

✔️ Elevate your routing architecture by introducing admin.php inside the web 📁, dedicated solely to admin-centric web routes

✔️craft a user.php in the same locale, encapsulating all user-level interactions.

Organize and register custom routes files in Laravel
web related routes organized into web/

🎯 Here is the tricky part:

Open bootstrap/app.php - this file acts as the conductor for your application startup, creating the core Laravel instance and registering essential services (like authentication) and middleware (like request security) for your entire application. This file simplifies configuration compared to previous versions by directly incorporating most of the setup.

You may notice how by default, Laravel registers the web.php and console.php using the withRouting method.

Registering routes in Laravel app
route registration out of the box in bootstrap/app.php

Now, all we need to do is register our various web route files in a similar fashion.

We’ll also consider prefixing user routes with the /user path and admin-level routes with the /admin path, ensuring the implementation of relevant middleware for each.

Register additional custom routes files in Laravel
Register your additional custom routes files

see how we were able to set the prefix & middleware! you can customize them as per your app

To simplify this example, I’ve applied the auth middleware only to the admin routes. However, in a real-world scenario, I’d use the auth middleware (auth:sanctum) for both user and admin routes to ensure users are logged in first. Additionally, I’d implement a specific admin middleware to differentiate between normal users and those with admin-level access.

For your convenience, I’ve included the contents of the withRouting method below. This snippet is ready for you to integrate directly into your codebase, offering a streamlined way to handle your routing. Feel free to customize it as needed to fit your application's requirements.

->withRouting(
web: __DIR__ . '/../routes/web/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
then: function () {
Route::middleware('web')
->group(function () {
Route::prefix('user')
->group([
__DIR__ . '/../routes/web/user.php',
]);
Route::middleware('auth:sanctum')
->prefix('admin')
->group([
__DIR__ . '/../routes/web/admin.php',
]);
});
},
)

⛳️ The final step:

Let’s introduce some straightforward route registrations in both the user.php and admin.php route files. We’ll keep all the publicly accessible routes in the web.php like /contact etc.

user route register laravel
routes/web/admin.php
admin route register laravel
routes/web/user.php
generic public route register laravel
routes/web/web.php

🌟 The Reward Awaits:

Now run the app (php artisan serve) navigate to /user/test and /contact in your browser. You’ll marvel at how Laravel recognizes all the routes we’ve just registered 😱.

Successfully separating different routes for your app not only cleans up the architecture but also simplifies maintenance, doesn’t it?

Thanks for reading! Have Fun, Happy Coding 🤙

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sourav Rakshit
Sourav Rakshit

Written by Sourav Rakshit

🚴‍♂️ an explorer 🪐 writing programs ⌨ looking for cosmic secrets 🌓

Responses (10)

Write a response