Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active June 16, 2021 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam-ngu/c82383172be8524fdd337ba4cccf26bb to your computer and use it in GitHub Desktop.
Save sam-ngu/c82383172be8524fdd337ba4cccf26bb to your computer and use it in GitHub Desktop.
Laravel Route group: array syntax vs method syntax. Blog article:
<?php
// using array syntax
Route::group([
'middleware' => [
'auth:api',
\App\Http\Middleware\RedirectIfAuthenticated::class,
],
'prefix' => 'heyaa', // adding url prefix to all routes in this group
'as' => 'users.', // adding route name prefix to all routes in this group
'namespace' => "\App\Http\Controllers",
], function(){
Route::get('/users', [\App\Http\Controllers\UserController::class, 'index'])
->name('index');
// Once we defined the 'namespace' attribute, we can invoke our controller method
// by using the <controller_class>@<method> string
Route::post('/users', 'UserController@store')
->name('store');
Route::get('/users/{user}', [\App\Http\Controllers\UserController::class, 'show'])
->name('show');
Route::patch('/users/{user}', [\App\Http\Controllers\UserController::class, 'update'])
->name('update');
Route::delete('/users/{user}', [\App\Http\Controllers\UserController::class, 'destroy'])
->name('destroy');
});
<?php
// using method syntax
Route::middleware([
'auth:api',
\App\Http\Middleware\RedirectIfAuthenticated::class,
])
->name('users.') // you can use the as() method here as well
->namespace("\App\Http\Controllers")
->prefix('heyaa')
->group(function () {
Route::get('/users', [\App\Http\Controllers\UserController::class, 'index'])
->name('index');
Route::get('/users/{user}', [\App\Http\Controllers\UserController::class, 'show'])
->name('show');
Route::post('/users', [\App\Http\Controllers\UserController::class, 'store'])
->name('store');
Route::patch('/users/{user}', [\App\Http\Controllers\UserController::class, 'update'])
->name('update');
Route::delete('/users/{user}', [\App\Http\Controllers\UserController::class, 'destroy'])
->name('destroy');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment