Route Groups
Lendly's admin pages all start with /admin, all need a logged-in user, and all have names starting with admin.. Writing those three things on every admin route is noisy and easy to forget once. Forget the login check on one route and you have a security hole. A route group says it once for all of them.
The rule
Say the shared part once; every route inside inherits it.
A group is a set of settings followed by ->group() and a closure holding the routes:
Route::middleware('auth')
->prefix('admin')
->name('admin.')
->group(function () {
Route::get('/books', [AdminBookController::class, 'index'])->name('books');
Route::get('/members', [AdminMemberController::class, 'index'])->name('members');
});What each setting does to the routes inside:
middleware('auth'): runs the middleware before every route, so guests are sent to log in.prefix('admin'): adds/adminin front of every URI, so/booksbecomes/admin/books.name('admin.'): gluesadmin.onto the front of every route name, sobooksbecomesadmin.books. The trailing dot is yours to include.controller(...): lets routes name only the method.
Route::controller(LoanController::class)->group(function () {
Route::get('/loans', 'index');
Route::post('/loans', 'store');
});Groups can be nested, and the settings stack up: prefixes join with /, names join end to end, and middleware lists are combined.
The shortcut
To predict a grouped route, build it outside-in: start from the outermost group, add each layer's prefix, name and middleware, then the route's own part last.
Outer group
middleware('auth')->prefix('admin')->name('admin.').
The trap is forgetting the dot in name('admin'). The names become adminbooks and adminmembers, and route('admin.books') fails.
Drills
Answer fast — trust the rule.
Inside Route::prefix('shop')->group(...), what URI does Route::get('/cart', ...) get?
A group uses name('admin') without a dot, and a route inside is named books. What is the full name?
Why put all admin routes in one middleware('auth') group?
Inside Route::controller(BookController::class)->group(...), how does a route name its action?
Remember
- Say the shared part once; every route inside inherits it.
- Build grouped routes outside-in: prefixes, names and middleware stack.
- Trap: the name prefix needs its own trailing dot.
