Using route groups in Laravel allows you to group several routes under a common middleware or prefix. This helps in organizing your routes and applying shared middleware to multiple routes at once. Here's how you can use route groups:
You can prefix a group of routes with a common URI segment. This is useful when you want to apply a prefix to a set of related routes. For example:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::prefix('admin')->group(function () {
Route::get('users', [UserController::class, 'index']);
Route::get('users/{id}', [UserController::class, 'show']);
// Other admin routes...
});
In this example, all routes defined within the admin
group will be prefixed with /admin
. So, accessing the users
route would be /admin/users
.
You can apply middleware to a group of routes. Middleware can be used for tasks like authentication, logging, etc. For example:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
Route::middleware(['auth'])->group(function () {
Route::get('dashboard', [AdminController::class, 'dashboard']);
Route::get('settings', [AdminController::class, 'settings']);
// Other routes requiring authentication...
});
In this example, all routes within the group will be protected by the auth
middleware, ensuring that only authenticated users can access them.
You can also nest route groups within each other to apply multiple prefixes or middleware. For example:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\UserController;
Route::prefix('admin')->middleware(['auth', 'admin'])->group(function () {
Route::prefix('users')->group(function () {
Route::get('/', [UserController::class, 'index']);
Route::get('/{id}', [UserController::class, 'show']);
// Other user routes...
});
// Other admin routes...
});
In this example, the /admin/users
routes are prefixed with both admin
and auth
middleware.
You can also prefix route names within a group. This helps in avoiding route name conflicts. For example:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Admin\UserController;
Route::name('admin.')->group(function () {
Route::prefix('users')->group(function () {
Route::get('/', [UserController::class, 'index'])->name('users.index');
Route::get('/{id}', [UserController::class, 'show'])->name('users.show');
// Other user routes...
});
// Other admin routes...
});
In this example, the users.index
route will have the name admin.users.index
.
Using route groups helps in keeping your routes organized and makes your code more readable and maintainable in Laravel applications.