Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Route Groups

Route groups 12 minA route group applies shared settings such as middleware, a URI prefix, a name prefix or a controller to every route inside it, so each route states only what is unique to it.

laravel / Route Groups

Explore each scene at your own pace.

01 · The rule

The rule

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 /admin in front of every URI, so /books becomes /admin/books.
  • name('admin.'): glues admin. onto the front of every route name, so books becomes admin.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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.