📂 Route Groups in Laravel (Prefix & Middleware)
Laravel allows you to group routes to apply shared attributes like middleware, namespaces, or URL prefixes. This helps keep your route definitions clean and organized.
📋 What are Route Groups?
Route groups let you avoid repeating attributes like middleware or prefix across multiple routes. Grouping makes your code more maintainable.
🔗 Prefixing Routes
Add a common path (e.g., /admin) to all routes in the group:
Route::prefix('admin')->group(function () {
Route::get('/dashboard', function () {
return 'Admin Dashboard';
});
Route::get('/users', function () {
return 'Manage Users';
});
});
Now accessible via:
/admin/dashboard/admin/users
🏷 Prefix with Named Routes
Route::prefix('admin')->name('admin.')->group(function () {
Route::get('/settings', function () {
return 'Admin Settings';
})->name('settings');
});
Named route usage: route('admin.settings')
🔐 Middleware Group
Apply middleware (e.g., auth) to protect multiple routes:
Route::middleware(['auth'])->group(function () {
Route::get('/profile', function () {
return 'User Profile';
});
Route::get('/dashboard', function () {
return 'User Dashboard';
});
});
Only authenticated users can access these routes.
prefix, middleware, and name together for advanced grouping.
Route::prefix('admin')
->middleware(['auth', 'isAdmin'])
->name('admin.')
->group(function () {
Route::get('/dashboard', fn () => 'Admin Panel')->name('dashboard');
});


