Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Route Model Binding

Route model binding 12 minWhen a route parameter's name matches a type-hinted model argument, Laravel fetches that model automatically and sends a 404 if it does not exist.

laravel / Route Model Binding

Explore each scene at your own pace.

01 · The rule

The rule

Route Model Binding

Look at almost any show, edit or update method and its first line is the same: take the id, look up the record, 404 if it is missing. Lendly would repeat Book::findOrFail($id) in dozens of places. Route model binding makes Laravel do that line for you.

The rule

Same name, model type: Laravel fetches it or sends 404.

Before:

Route::get('/books/{id}', [BookController::class, 'show']);

public function show(string $id)
{
    $book = Book::findOrFail($id);
    return view('books.show', ['book' => $book]);
}

After:

Route::get('/books/{book}', [BookController::class, 'show']);

public function show(Book $book)
{
    return view('books.show', ['book' => $book]);
}

Two things must line up:

  1. The URI segment is {book}, and the argument is $book. The names match.
  2. The argument is type-hinted with the model, Book.

Then, for /books/12, Laravel runs the lookup by primary key and passes in the finished Book. For /books/9999 with no such row, it sends a 404 and your method never runs.

Looking up by another column. Put the column after a colon in the URI:

Route::get('/books/{book:slug}', [BookController::class, 'show']);

Now /books/dune fetches the book whose slug is dune. To make a column the default for every route, override getRouteKeyName() on the model to return 'slug'.

It works in closures too: Route::get('/books/{book}', fn (Book $book) => $book->title);.

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