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/7In 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, shorterA few details:
route()returns a full URL, including the domain fromAPP_URLor the current request. Passfalseas 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.
The shortcut
Treat the URI as a private detail of the routes file. Everywhere else, templates, redirects and emails, speak only in names. Then a URL change is a one-line edit.
Before
Route::get('/books/{id}', ...)->name('books.show'), and 20 templates callroute('books.show', ...).
The trap is naming routes and then still hard-coding href="/books/7" in a template. That link breaks on the next move.
Drills
Answer fast — trust the rule.
How do you give a route the name loans.index?
A route is /books/{id} named books.show. What does route('books.show', ['id' => 4], false) return?
What does route('books.index', ['page' => 3]) give if books.index is /books with no parameters?
You change a named route's URI. What else must you edit for links built with route()?
Which line redirects to a named route after saving?
Remember
- Name the route once; build every URL with
route(). - The URI is private to the routes file. Everything else speaks in names.
- Trap: a hard-coded
hrefdefeats the name and breaks on the next move.
