DEV Community

Wade Zimmerman
Wade Zimmerman

Posted on

Laravel - Separate Routes into Custom Route Files

Have you ever lost your train of thought while looking for a route in your Laravel project?

Scenario - Use Case

Odds are you have routes for admin dashboards, user preferences, content feeds, payment gateways, etc. How do you keep all these routes organized while staying organized?

Answer

Adding a custom route file is great for applying middleware and prefixes to every route in the file. The RouteServiceProvider provides an interface for registering additional routers.

How to Add a Custom Route File in Laravel

Open your app/Providers/RouteServiceProvider.php file in your favorite editor. In the boot method, you can register custom routers:

Laravel custom route file

By default, Laravel registers a file for pages in the web.php file, and API endpoints in the api.php file. Each route group is assigned to a middleware group which is configurable in the app/Http/Kernel.php file:

Laravel Middelware Groups

To define a custom route file like dashboard.php start by adding a route group, and consider attaching a middleware group for more control:

Laravel custom dashboard route file

Defining routes for a dashboard will be scoped to the prefix and middleware defined in the RouteServiceProvider class.

Laravel Resource routes

Conclusion

Dedicated route files is an easy way to clean up your Laravel project. For more quick Laravel tips, follow me on X https://x.com/WadeCodeZ

Top comments (0)