Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 67 ยท Routing and Controllers

Route Groups and Model Binding

Share prefixes, names and middleware with route groups, then let Laravel turn URL segments into Eloquent models with implicit, explicit and scoped binding.

Once an application has more than a handful of routes, two kinds of repetition appear. First, many routes share the same settings: they all live under /admin, all need a logged-in user, all have names starting with admin.. Second, almost every route with or in its URI begins by looking that record up in the database and returning a 404 if it does not exist. Laravel removes both: route groups share settings, and route model binding does the lookup for you.

This lesson builds on routing basics. As before, the Laravel code is read-only, and the runnable examples are plain-PHP stand-ins that show the mechanism. Eloquent itself arrives later in Eloquent models and CRUD; for now you only need to know that a model is a PHP class representing a database row.

Route groups

A group applies attributes to every route defined inside its closure. The fluent style reads left to right:

PHP
use Illuminate\Support\Facades\Route;

Route::prefix('admin')
    ->name('admin.')
    ->middleware(['auth', 'verified'])
    ->group(function () {
        Route::get('/', fn () => 'dashboard')->name('dashboard');          // GET /admin       admin.dashboard
        Route::get('/users', fn () => 'users')->name('users.index');       // GET /admin/users admin.users.index
    });

Three attributes cover most needs:

  • prefix('admin') puts /admin in front of every URI.
  • name('admin.') puts admin. in front of every route name. Note the trailing dot; Laravel concatenates exactly what you write.
  • middleware([...]) runs the listed middleware for every route inside.

Groups nest, and the inner group adds to the outer one: prefixes and names are concatenated, middleware lists are merged. Other group helpers include domain('{tenant}.example.com') for subdomain routing and scopeBindings(), which you will meet below.

Controller groups

When many routes use the same controller, name it once:

PHP
use App\Http\Controllers\PostController;

Route::controller(PostController::class)->group(function () {
    Route::get('/posts', 'index')->name('posts.index');
    Route::get('/posts/{post}', 'show')->name('posts.show');
    Route::post('/posts', 'store')->name('posts.store');
});

Each route now names only the method. Controllers goes deeper, including resource routes that generate seven routes in one line.

flowchart TD
    G["Route::prefix('admin')<br/>->name('admin.')<br/>->middleware('auth')"] --> R1["GET /admin<br/>admin.dashboard"]
    G --> I["Inner group: prefix('users')<br/>name('users.')"]
    I --> R2["GET /admin/users<br/>admin.users.index"]
    I --> R3["GET /admin/users/{user}<br/>admin.users.show"]

An inner group inherits everything from the outer group and adds its own prefix and name part.

Implicit model binding

Without binding, a show-page route looks up the record itself:

PHP
Route::get('/posts/{id}', function (string $id) {
    $post = Post::find($id);
    abort_if($post === null, 404);
    return view('posts.show', ['post' => $post]);
});

With implicit binding, you type-hint the model and name the argument after the placeholder:

PHP
use App\Models\Post;

Route::get('/posts/{post}', function (Post $post) {
    return view('posts.show', ['post' => $post]);
});

Laravel sees that $post is an Eloquent model whose name matches , queries posts by primary key using the URL value, and passes the result in. If no row matches, the framework throws a ModelNotFoundException, which is rendered as a 404 response. Your code only runs when the record exists, which also means fewer places to forget a check.

Binding by another column

IDs in URLs are fine, but slugs are friendlier. Choose the column inline with a colon:

PHP
Route::get('/posts/{post:slug}', fn (Post $post) => $post->title);

Or make a column the default for a model by overriding getRouteKeyName():

PHP
class Post extends Model
{
    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}

Other options exist for special cases. Soft-deleted models are not found by default, and you can allow them with ->withTrashed() on the route. A route can also replace the 404 with its own response using ->missing(fn () => redirect()->route('posts.index')). Backed enums can be type-hinted too; an unknown value gives a 404.

Scoped bindings

Consider /users/{user}/posts/{post:slug}. Slugs are usually unique only per author, so "engines" may exist under two users. When you use a custom key for a child binding like this, Laravel automatically scopes it: the post is looked up through the user's posts relationship, so it must belong to that user, or the result is a 404. If you want that behavior with ordinary keys too, ask for it explicitly:

PHP
Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) {
    return $post->title;
})->scopeBindings();

Scoping is also a security feature. Without it, someone could request /users/1/posts/99 where post 99 belongs to user 2, and your page would show a post under the wrong owner. Never rely on the URL hierarchy being honest unless the lookup enforces it.

Explicit binding

Sometimes the segment does not map to a plain column lookup. Register the rule yourself in AppServiceProvider::boot():

PHP
use App\Models\User;
use Illuminate\Support\Facades\Route;

// Always resolve {user} by username, for every route:
Route::model('user', User::class);

// Or write any resolution logic:
Route::bind('user', function (string $value) {
    return User::where('username', $value)->firstOrFail();
});

Route::model only declares which class a placeholder refers to, which is useful when the argument name differs from the model name. Route::bind gives you the full callback.

Fallback routes and caching

A fallback route runs when nothing else matches, replacing the default 404 page for requests that reach the router:

PHP
Route::fallback(fn () => response()->view('errors.custom-404', status: 404));

Register it last. For speed in production, run php artisan route:cache: it compiles every route into one file so Laravel skips parsing your route files on each request, and php artisan route:clear removes the cache. Do it during deployment and clear it while developing, otherwise changes to your route files seem to be ignored. Keeping route logic in controllers rather than long closures is the habit that always works with caching.

A binding resolver in plain PHP

The stand-in below mimics the idea of binding: it takes a URI template such as /users/{user:username}/posts/{post:slug}, extracts each segment, looks up the matching "model" in some in-memory tables, and fails with a 404 when a record is missing. It also demonstrates scoping, using two authors who both have a post with the slug engines. The tables are arrays, not Eloquent, and real Laravel builds SQL queries instead.

PHP Resolving URL segments into records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Compare the two /users/ada/posts/kernels lines. With scoping, the post belongs to Linus, so Ada's URL is a 404. Without scoping, the lookup happily finds the post by slug alone and shows it under the wrong user.

Group attributes in plain PHP

Groups are a stack. Entering a group pushes attributes, leaving it pops them, and every route defined in between reads the merged result. The stand-in below uses that idea with a fluent builder like Laravel's.

PHP A tiny route group builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice how the inner group's middleware is added to the outer one rather than replacing it, exactly as in Laravel.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Route::prefix('admin')->name('admin.') do to a route named dashboard at URI /?

    The prefix is placed in front of the URI and the name part in front of the route name, so the route is GET /admin and is named admin.dashboard.
  2. 2. What happens with implicit model binding when no record matches the URL value?

    Your action never runs for a missing record; the exception is converted into a 404, unless you customize it with missing().
  3. 3. Why do scoped bindings matter for /users/{user}/posts/{post:slug}?

    Slugs are often only unique per author. Scoping restricts the child lookup to the parent's relationship and prevents showing a record under the wrong owner.
  4. 4. Which line makes {post} resolve by slug in a single route?

    The colon syntax {post:slug} names the column to search. Alternatively override getRouteKeyName() on the model.

Summary

  • Groups share prefix, name, middleware, controller and domain settings; nested groups combine them.
  • Implicit binding turns plus a Post $post argument into a looked-up model, with a 404 when it is missing.
  • Use {post:slug} or getRouteKeyName() to bind by a column other than the primary key.
  • Scoped bindings make child lookups go through the parent, which prevents records appearing under the wrong URL.
  • Route::model and Route::bind handle explicit binding; Route::fallback handles unmatched requests.
  • route:cache speeds up production routing; route:clear removes it.

Next: Controllers