Laravel for Beginners – Learn to Build Full-Stack Web Apps

Loading video...

Named Routes

You can also define name for each route.

Route::get("/about", function() {
    // ...
})->name("about");

What is the point of assigning name to a route?

When we want to generate URLs without route names the only way to generate URLs in our application is the following.

$aboutPageUrl = "/about"
// Use $aboutPageUrl in navigation:
// <a href="USE_IT_HERE">About</a>

Imagine that this URL is used in several places on your website:

  1. In the main header navigation
  2. In the footer navigation
  3. And maybe in the sidebar

At some point if you decide to update the URL from /about into /about-us you have to update it in all 3 places.

In reality it might be used in much more than just 3 places. You might miss some of the places and did not update which leads to broken and not working URLs.

Once, you assign name to your route you can generate routes by name.

$aboutPageUrl = route("about"); // route() function accepts name of the route as argument
// Use $aboutPageUrl in navigation:
// <a href="USE_IT_HERE">About</a>

If you have all your URLs generated with route() function and then you change the route from /about into /about-us

Route::get("/about-us", function() {
    // ...
})->name("about");

Laravel will generate proper URLs and you will not have broken URLs.

Discussion

Sign in to join the discussion.

No comments yet. Be the first to start the discussion!