Named Routes

Give routes a name so you can reference them without hardcoding URLs.

SyntaxRoute::get('/profile', $cb)->name('profile');

Chaining ->name('...') onto a route lets you refer to it by name. Then generate its URL with the route() helper. If the URL ever changes, every link updates automatically.

Example

Example · php
use Illuminate\Support\Facades\Route;

Route::get('/dashboard', function () {
    return 'Dashboard';
})->name('dashboard');

// Elsewhere, build the URL by name:
// $url = route('dashboard');

When to use it

  • A Blade template uses route('products.show', $product) to generate the link to a product page, so renaming the URL in routes/web.php does not require updating any templates.
  • A controller redirects users after login with redirect()->route('dashboard') instead of hardcoding the URL path.
  • A middleware checks the current route name with Route::is('admin.*') to decide whether to enforce additional two-factor authentication.

More examples

Define and link to a named route

Naming a route with ->name() decouples the URL path from the code that links to it, so path changes are made in one place.

Example · php
// routes/web.php
Route::get('/products/{product}', [ProductController::class, 'show'])
    ->name('products.show');

// In a Blade template
<a href="{{ route('products.show', $product) }}">View Product</a>

// In a controller
return redirect()->route('products.show', ['product' => 1]);

Name an entire resource route group

Route::resource() names all seven CRUD routes automatically using the resource name as a prefix, following the posts.action convention.

Example · php
Route::resource('posts', PostController::class);
// Automatically names: posts.index, posts.create, posts.store,
//   posts.show, posts.edit, posts.update, posts.destroy

$url = route('posts.edit', $post);
// => /posts/42/edit

Check the current route name

Route::is() and request()->routeIs() accept wildcard patterns to match groups of related routes by name prefix.

Example · php
use Illuminate\Support\Facades\Route;

// In a middleware or controller
if (Route::is('admin.*')) {
    // Any route whose name starts with 'admin.'
    $this->enforce2FA();
}

// In Blade
@if (request()->routeIs('products.*'))
    <p>You are browsing products.</p>
@endif

Discussion

  • Be the first to comment on this lesson.