logo
podcast Podcast
get help Get Unstuck

How are duplicate routes resolved?

Order is important

Joel Clermont
Joel Clermont
2024-11-19

In response to the tip last week about named routes, someone replied to ask "What happens if you have two routes with the same name? Which one wins?"

This actually raises a larger question: How are duplicate routes handled in Laravel in general?

It helps to understand how Laravel takes your routes file and converts it into a route collection.

The routes file is processed from top to bottom, definition by definition. Each route definition is converted to one or more routes (for example, resource route definitions can generate multiple routes).

Those routes are added to the route collection where the lookup value (or key) of each route is the route URL. So when a duplicate is encountered, the later definition wins.

This is true whether the collision is in the route URL or the route name.

This is why it's important to list wildcard or more general routes first, and then more specific routes later.

Here to help,

Joel

P.S. Every month, members of the Mastering Laravel community can join a live dev call we host for Q&A, code reviews, and more.

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.