Laravel Route File Cleanup
Tutorials January 24, 2018 1 min read 432 views

Laravel Route File Cleanup

A quick tip for keeping your Laravel route files clean and organized using separate route files.

Z

Zach Robichaud

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

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!