Route group namespacing

Submitted by stidges - 10 years ago

I like namespacing my controllers. I think it cleans up my structure a bit, and prevents me from having to 'composer dump-autoload' everytime I make a new controller. Though it is very convenient to namespace your controllers, your routes file can quickly become very messy. Luckily, Laravel 4.1 offers a great solution for this, namely the 'namespace' option in Route::group().

// In Laravel 4.0 your routes would look something like this
Route::get('/', array('as' => 'home', 'uses' => 'Controllers\HomeController@index'));
Route::get('admin/dashboard', array('as' => 'admin.dashboard.index', 'uses' => 'Controllers\Admin\DashboardController@index'));
// etc. This gets messy very quickly.

// Laravel 4.1 allows us to write this a lot cleaner:
Route::group(array('namespace' => 'Controllers'), function()
    Route::get('/', array('as' => 'home', 'uses' => 'HomeController@index'))
    Route::group(array('namespace' => 'Admin'), function()
        // Notice how, by nesting route groups, the namespace will automatically
        // be nested as well!
        Route::get('admin/dashboard', array('as' => 'admin.dashboard.index', 'uses' => 'DashboardController@index'));