Neon Tsunami

Named route conventions in Laravel

September 02, 2014

Piggy-backing off my last post is the usage of named routes on Laracasts. I've noticed the use of things like users_path and user_path as named routes in some of the applications being built on that site.

Route::get('users', [
    'as' => 'users_path',
    'uses' => 'UsersController@index'
]);

If you've used Rails, these kind of helpers probably seem pretty familiar to you (and they're really helpful, I've actually made a PR or two to try and bring similar functionality to Laravel). However I find this flies right in the face of the conventions already in Laravel. Take a look at this resource, for example.

Route::resource('users', 'UsersController');

If you were to run php artisan routes now, you'll see the Laravel convention for named routes show. It's slightly more verbose, but it's very clear.

  • users.index
  • users.create
  • users.store
  • users.show
  • users.edit
  • users.update
  • users.destroy

These seven named routes map to seven methods on a resource controller (which can be generated by Artisan, also) and also to the four HTTP methods to be RESTful. Because of this, when defining my routes I try to always stick to this convention also. I find that it keeps a project a lot more organised, and it takes less time to think about what users.store does, as opposed to users_path.

Route::get('users', [
    'as' => 'users.index',
    'uses' => 'UsersController@index'
]);

Again, this is just me showing how I do projects (and how our coding style guide demands it at work). Free to consider your options, but I like this.


A blog about Laravel & Rails, written by Dwight Watson.