Skip to the workspace
Pebellslearn by building
Routing  ›  Capstone Project

Named Routes

Named routes 15 minNaming a route lets code build its URL with route() and redirect to it by name, so URIs can change without breaking every link.

laravel / Named Routes

Explore each scene at your own pace.

01 · The rule

The rule

Named Routes

Lendly's book page is linked from the home page, search results, a member's loan history, emails and more. If those links are typed as "/books/" . $id, then moving the page to /library/{id} means hunting down every one. Named routes let you link to the route, not the address.

The rule

Name the route once; build every URL with route().

Give the route a name:

Route::get('/books/{id}', function (string $id) {
    return view('books.show', ['id' => $id]);
})->name('books.show');

Then generate its URL anywhere with the route() helper, passing parameters as an array:

route('books.show', ['id' => 7]);   // http://lendly.test/books/7

In Blade:

<a href="{{ route('books.show', ['id' => $book->id]) }}">{{ $book->title }}</a>

Redirects use the name too:

return redirect()->route('books.show', ['id' => 7]);
return to_route('books.show', ['id' => 7]);   // same thing, shorter

A few details:

  • route() returns a full URL, including the domain from APP_URL or the current request. Pass false as the third argument for just the path: route('books.show', ['id' => 7], false) gives /books/7.
  • Extra array keys that are not parameters become the query string: route('books.index', ['page' => 2]) gives /books?page=2.
  • Names must be unique. The convention is resource.action: books.index, books.show, loans.store.
  • Asking for a name that does not exist throws an error, so typos are caught at once instead of producing dead links.
  • request()->routeIs('books.*') checks whether the current page belongs to a name pattern, which is handy for highlighting menu items.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.