DEV Community

Cover image for 3 Ways to Keep Your Laravel Routes Organized
ryan
ryan

Posted on

3 Ways to Keep Your Laravel Routes Organized

Introduction

Laravel routing allows us to easily map a URI pattern to a particular controller, or method. It's easy to let routing get unorganized if we don't follow a pattern.

In this post, we'll go over a simple pattern that puts namespace, routing groups, and common HTTP operations into a single component.

  • Use route groups
  • Apply a name to the route group
  • Use a common namespace for all operations under the route group.

Before

use Illuminate\Support\Facades\Route;

Route::namespace('Site\Secrets')
    ->get('/sites/{site}/secrets', 'SecretController@get')
    ->name('site.secrets.index');

Route::namespace('Site\Secrets')
    ->get('/sites/{site}/secrets', 'SecretController@post')
    ->name('site.secrets.new');

Route::namespace('Site\Secrets')
    ->get('/sites/{site}/secrets', 'SecretController@delete')
    ->name('site.secrets.delete');

The above pattern is fine, but we're repeating ourselves A LOT. Just take a look at how many times we typed sites/{site}/secrets. There's a better way to make our route definitions easier to read, maintainable, and overall better.

After

use Illuminate\Support\Facades\Route;

Route::namespace('Site\Secrets')->name('site.secrets.')
    ->prefix('/sites/{site}/secrets')->group(function () {
        Route::get('/', 'SecretController@get')
            ->name('index');
        Route::post('/', 'SecretController@post')
            ->name('new');
        Route::delete('/{secret}', 'SecretController@delete')
            ->name('delete');
});

Notice how we're using Route Groups. This allows us to apply common settings to each Route:: call inside the group callback.

All routes defined in our group will use the fully qualified PHP namespace of Site\Secrets. Laravel will resolve the fully qualfied controller class name to \App\Http\Controllers\Site\SecretsController.

If we're not sure where \App\Http\Controllers comes from, then we can go to line 17 of the RouteServiceProvider.php file. In this file, Laravel defines the namespace to be applied to our controller routes.

This means, that every route defined in our callback will have site.secrets. prepended to its name. In effect, the
index route would actually be site.secrets.name

Conclusion

As software engineers, we should strive to write maintainable and easy-to-read code.

Top comments (0)