Laravel — P22: Named Routes

Unlocking the Power of Laravel: Mastering Named Routes

Routes change. “We don’t like contact-us; can it just be contact? We also don’t like about-us; can it just be about?” These are the kind of questions that you get from your amazingly awesome Marketing team that’s there to only make your life super simple all the time.

Laravel — P21: Artisan Intro and Route List

Does it matter that you have a ton of components that all have the route hard-coded in? How many <a href="/about-us">About</a> will you have to modify to <a href="/about">About</a>?

Luckily, there are named routes. Once you set a name for your route, you reference the name, so it doesn’t matter what you put in it. Think of it like a variable. We can call our named route about-page and it would not matter if the about-page is set to about-us or about, it’ll always show the intended page.

Let’s see it in action. We ended our Component Layouts article with a pretty nice template.

https://medium.com/geekculture/laravel-p19-component-layouts-bf860107a9ec

What I would like to do now is add a link to our buttons. There are two buttons:

  • Get Started
  • Learn More

 

 

We’ll start this article like all the other ones, by creating a route to our new home-page. I’m going to call our home-page view: home-named.

 

The index.blade.php file within it will contain the following code. It’s the same code from the Component Layouts article.

<x-layouts.app title="{{ $title }}">
    <div class="flex bg-white" style="height:600px;">
        <div class="flex items-center text-center lg:text-left px-8 md:px-12 lg:w-1/2">
            <div>
                <h2 class="text-3xl font-semibold text-gray-800 md:text-4xl">Named <span class="text-indigo-600">Routes</span></h2>
                <p class="mt-2 text-sm text-gray-500 md:text-base">We're building a layout using template inheritance. Blanditiis commodi cum cupiditate ducimus, fugit harum id necessitatibus odio quam quasi, quibusdam rem tempora voluptates. Cumque debitis dignissimos id quam vel!</p>
                <div class="flex justify-center lg:justify-start mt-6">
                    <a class="px-4 py-3 bg-gray-900 text-gray-200 text-xs font-semibold rounded hover:bg-gray-800" 
                       href="#">
                        Get Started
                    </a>
                    <a class="mx-4 px-4 py-3 bg-gray-300 text-gray-900 text-xs font-semibold rounded hover:bg-gray-400" 
                       href="#">
                        Learn More
                    </a>
                </div>
            </div>
        </div>
        <div class="hidden lg:block lg:w-1/2" style="clip-path:polygon(10% 0, 100% 0%, 100% 100%, 0 100%)">
            <div class="h-full object-cover" style="background-image: url(https://images.unsplash.com/photo-1498050108023-c5249f4df085?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1352&q=80)">
                <div class="h-full bg-black opacity-25"></div>
            </div>
        </div>
    </div>
</x-layouts.app>

We can add the links to our Get Started and Learn More href attributes.

<a class="px-4 py-3 bg-gray-900 text-gray-200 text-xs font-semibold rounded hover:bg-gray-800"
   href="/get-started">
    Get Started
</a>
<a class="mx-4 px-4 py-3 bg-gray-300 text-gray-900 text-xs font-semibold rounded hover:bg-gray-400"
   href="/learn-more">
    Learn More
</a>

Let’s get our route’s going. We’ll need three different routes:

  • The first route is to load our home-named/index view.
  • The next route is our get-started route.
  • The third route is our learn-more route.
<?php
Route::get('/home-named', function() {
    return view('home-named/index', [
        'title' => 'Named Routes',
    ]);
});

Route::get('/get-started', function() {
    return "Get Started";
});

Route::get('/learn-more', function() {
    return "Learn More";
});

If we visit our page, we get to see our page. Clicking on the links will take us to the intended pages, which just produce a string at the moment.

 

Now, if we wanted to change the get-started route to first-steps, we have to modify the <a href="/get-started"> tag in the home-named/index view and we also have to modify the route. Why would we do that to ourselves? Let’s just create a named route. We simply chain on a name() to the end of our Route and set the name that we want.

<?php
Route::get('/get-started', function() {
    return "Get Started";
})->name('getting-started');

Route::get('/learn-more', function() {
    return "Learn More";
})->name('learn-more');

Now that we have it set, we just need to modify our view. We can use the route() function inside of our component to inject the proper route for the name that we pass.

<a class="..."
   href="{{ route('getting-started') }}">
    Get Started
</a>
<a class="..."
   href="{{ route('learn-more') }}">
    Learn More
</a>

If we refresh our page and click on our links, we’ll see that it takes us to where we want to go. The only thing to remember is that we need to make our route names unique.

Passing Arguments to Named Routes

There are times when we need to pass arguments to our routes. For example, let’s say that we pass an id to our learn-more route.

<?php
Route::get('/learn-more/{id}', function($id) {
    return "Learn More: " . $id;
})->name('learn-more');

How do we pass that from our view now? Before it was pretty simple:

<a href="/learn-more/42">Learn More</a>

It’s not too bad with named routes either. The route() function accepts a second argument, which is an associative array with the keys equal to the URL arguments. Since we have an id argument, we’ll need to pass that.

<a href="{{ route('learn-more', ['id' => 42]) }}">
    Learn More
</a>

What if we have more than one argument? Same thing.

<?php
Route::get('/learn-more/{id}/department/{department}', function($id, $department) {
    return "Learn More: " . $id . " for " . $department;
})->name('learn-more');

Look how messy that route looks. Not with our named routes.

<a href="{{ route('learn-more', ['id' => 42, 'department' => 'IT']) }}">
    Learn More
</a>

Do we need the keys in the associative array? Can we just pass an array of values?

<a href="{{ route('learn-more', [42, 'IT']) }}">
    Learn More
</a>

We actually can, but I prefer to explicitly state what they are. You will need to place them in the order that they’re received in the route if you want everything to function properly.

Not much more to named routes. See you in the next one when we tackle route groups.

Laravel Series

Continue your Laravel Learning.

Laravel — P21: Artisan Intro and Route List

Laravel Essentials: Exploring Artisan and Navigating Routes

Laravel – P21: Artisan Intro And Route List

Dive into Laravel with an intro to Artisan commands & route listing. Streamline your workflow & enhance app structure efficiently.

Laravel — P22: Named Routes

Unlocking the Power of Laravel: Mastering Named Routes

Laravel – P22: Named Routes

Elevate your Laravel projects with named routes for cleaner code and easier navigation. Discover the essentials in our guide.

Laravel — P23: Route Groups

Unlocking the Power of Laravel: Mastering Named Routes

Laravel – P23: Route Groups

Elevate your Laravel projects with named routes for cleaner code and easier navigation. Discover the essentials in our guide.

Leave a Reply