logo
podcast Podcast
get help Get Unstuck

Always use named routes

Future developers will thank you

Joel Clermont
Joel Clermont
2024-11-06

When I first join a project, I like to explore the code to see how features are built and how the code is structured.

If I'm in a controller and I see a redirect to another route, I like to be able to click through and see where it's going. Same thing if I see a form that submits to a route.

But if the route is just defined as a string, you lose that ability.

Using named routes is also important when refactoring and trying to find all the places that reference this route. Without that knowledge, you lose confidence in the refactor.

Even worse than a string path, sometimes I'll see a path built up with concatenation, where a few parts are joined together with variables shoved in. This makes it now almost impossible to find even with a global find/replace, leading to broken code.

Laravel provides so many helpers in Blade, controllers, and tests to make it easy to always reference a route name:

// in a Blade view, building a link
<a href="{​{ route('profile') }}">Profile</a>

// in a controller, doing a redirect
return redirect()->route('profile');

// in a test, making a request
$this->get(route('profile'));

// and even in assertions
$response->assertRedirectToRoute('profile');

There are very few things I categorically say you should always do, but I think named routes is a safe thing to be dogmatic about.

Do future developers a favor and always use named routes.

Here to help,

Joel

P.S. Hey, maybe I'll be that future developer one day! Aaron and I love helping out on Laravel projects.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.