MWZ

MINDWAREZONE

What are named routes?

  • Named routes are routes that have a unique name assigned to them.
  • They allow you to generate URLs or redirects using the route name instead of hardcoding URLs.
  • If the URL changes later, you only need to update the route definition, not every place where the URL is used.
  • Named routes improve code readability and maintainability.
  • They are commonly used in redirects, Blade views, controllers, and route model binding.

Defining a Named Route

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

Generating a URL

$url = route('dashboard');
            

Redirecting to a Named Route

return redirect()->route('dashboard');
            

Using Named Routes in Blade

<a href="{{ route('dashboard') }}">Dashboard</a>
            

Named Route with Parameters

Route::get('/posts/{post}', [PostController::class, 'show']) ->name('posts.show');
            

Generate the URL:

route('posts.show', ['post' => 1]);
            

Output:

/posts/1
            

Benefits of Named Routes

  • Easier URL generation.
  • Avoids hardcoded URLs.
  • Simplifies redirects.
  • Improves maintainability.
  • Makes the code more readable.