phplaravellaravel-7laravel-route

Laravel 7.x name routes in routes group


I'm learning Laravel and I wanna group some routes using prefix and naming each route so I got something like this

Route::prefix('customers')->group(
    function(){
        Route::get('/', 'CustomerController@index')->name('customers.index');
        Route::get('/create', 'CustomerController@create')->name('customers.create');
        Route::post('/', 'CustomerController@store')->name('customers.store');
});

I want to avoid writing 'customers.' in every route name.

I have tried with group and name but it doesn't recognize the route name prefix 'customers.'

Route::group(['prefix' => 'customers', 'name' => 'customers.'],
    function(){
        Route::get('/', 'CustomerController@index')->name('index');
        Route::get('/create', 'CustomerController@create')->name('create');
        Route::post('/', 'CustomerController@store')->name('store');
});

The other way I found was with as and use but it seems to much code, and doesn't look kind of clean, actually the first one looks like a cleaner way.

Route::group([
    'prefix' => 'customers',
    'as' => 'customers.'
    ],
    function(){
        Route::get('/', ['as'=>'index', 'uses' => 'CustomerController@index']);
        Route::get('/create', ['as'=>'create', 'uses' => 'CustomerController@create']);
        Route::post('/', ['as'=>'store', 'uses' => 'CustomerController@store']);
});

Is there a better way to do it?


Solution

  • RESTful Resource controller

    A RESTful resource controller sets up some default routes for you and even names them.

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

    Gives you these named routes:

    Verb          Path                        Action  Route Name
    GET           /users                      index   users.index
    GET           /users/create               create  users.create
    POST          /users                      store   users.store
    GET           /users/{user}               show    users.show
    GET           /users/{user}/edit          edit    users.edit
    PUT|PATCH     /users/{user}               update  users.update
    DELETE        /users/{user}               destroy users.destroy
    

    And you would set up your controller something like this (actions = methods)

    class UsersController extends BaseController {
    
        public function index() {}
    
        public function show($id) {}
    
        public function store() {}
    
    }
    

    You can also choose what actions are included or excluded like this:

    Route::resource('users', 'UsersController', [
        'only' => ['index', 'show']
    ]);
    
    Route::resource('monkeys', 'MonkeysController', [
        'except' => ['edit', 'create']
    ]);
    

    Taken from Laravel - Route::resource vs Route::controller