logo
podcast Podcast
get help Get Unstuck

Another reason to like named routes

It keeps getting better

Joel Clermont
Joel Clermont
2024-11-12

Yesterday, I was working in a project and I thought of an additional reason why I like using named routes that I didn't mention in the original article.

This particular project had portions of the app running on different subdomains. When we first joined the project, they had extra helpers in their tests to specify which subdomain should be used along with their string URLs.

But when I refactored this to use named routes, that extra helper became unnecessary. The named route automatically would resolve to the correct route without specifying the subdomain.

It looked like this:

// Before - without the domain, the URL will not work
$this->get($this->someDomainUrlHelper() . '/some-url');

// After - no special domain handling needed
$this->get(route('named.route'));

How does this work?

Internally, when Laravel compiles the route definitions, it also maintains two separate lookup lists for both actions and named routes. Think of it like an index on a database table.

So when you specify a named route (or action helper), it jumps right to the correct route without needing to resolve anything from a URL, or even from a domain plus URL.

Here to help,

Joel

P.S. Ever feel completely stuck on a problem in your Laravel app? Don't burn up days trying to solve it alone. Let's help you get unstuck.

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.