Laravel Route File Cleanup
A quick tip for keeping your Laravel route files clean and organized using separate route files.
Zach Robichaud
Table of Contents
Quick Tip for Laravel Routes
I'm writing this because I've watched several videos where developers add routes, route groups, and middleware directly into the main routes file. It quickly becomes messy.
Here's a cleaner approach: split your routes into separate files based on their purpose.
Example: Creating an Authenticated Routes File
If you need routes that require authentication, create a new file at routes/authed.php and add a mapping function to app/Providers/RouteServiceProvider.php:
/**
* Define the "authed" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapAuthedRoutes()
{
Route::middleware(['web', 'authed'])
->namespace($this->namespace)
->group(base_path('routes/authed.php'));
}
Make sure to call this function by adding $this->mapAuthedRoutes(); at the end of the map() function in the same file.
Benefits
You can specify middleware, prefixes, route names, and any other settings in the service provider. This keeps your actual route files clean and focused on just defining routes.
Resources
How was this article?
Related Posts
Decluttering Your Laravel Console: How to Hide Artisan Commands
Laravel ships with over 100 built-in Artisan commands, making it hard to find your custom commands in the noise. Learn how to create a clean, focused command list that only shows what your team actually uses—while keeping all commands fully functional.
If Searching for Quotes Breaks Your Software
When entering a single or double quote crashes your application, you likely have a SQL injection vulnerability. Here's what to do about it.
Testing Emails Safely
How to test email functionality without accidentally sending messages to real users.
Comments (0)
No comments yet. Be the first to share your thoughts!