Last Updated: February 25, 2016
·
1.685K
· mramsden

Laravel 4 Resource route names in group

Laravel 4 has an unfortunate side affect of the names that get created for resource routes inside groups with parameterised group prefixes.

For example say you have the following route configuration;

Route::group(['prefix' => 'continent/{continent}', function() {
    Route::resource('country', 'CountryController');
}

All of the resource's route names are prefixed by continent/{continent}. A patch was created for Laravel to assign a route name on a per-resource path basis;

Route::group(['prefix' => 'continent/{continent}', function() {
    Route::resource('country', 'CountryController', [
        'names' => [
            'index'   => 'country.index',
            'create'  => 'country.create',
            'store'   => 'country.store',
            'show'    => 'country.show',
            'edit'    => 'country.edit',
            'update'  => 'country.update',
            'destroy' => 'country.destroy'
        ]
    ]);
}

This can be annoying if you have to name all routes for your resource controller. Instead place this function at the top of your routes file, and save some legwork;

$prefixedResourceNames = function($prefix) {
    return [
        'index'   => $prefix . '.index',
        'create'  => $prefix . '.create',
        'store'   => $prefix . '.store',
        'show'    => $prefix . '.show',
        'edit'    => $prefix . '.edit',
        'update'  => $prefix . '.update',
        'destroy' => $prefix . '.destroy'
    ];
};

Now for your grouped resource it's as hard as doing;

Route::group(['prefix' => 'continent/{continent}', function() use ($prefixedResourceNames) {
    Route::resource('country', 'CountryController', ['names' => $prefixedResourceNames('country')]);
}

This should now drop the continent/{continent} part from the route scheme and just have prefix.action.