logo
podcast Podcast
get help Get Unstuck

Look for opportunities to group routes

It's not just about fewer lines of code

Joel Clermont
Joel Clermont
2024-09-04

There is a common piece of programming advice called the "rule of three" that says you shouldn't refactor to avoid duplication until you've repeated something three times. If you do it earlier, you run the risk of over-engineering and even settling on the wrong abstraction.

I'd like to be a bit contrary, but in a very specific context: grouping Laravel routes.

One of the internal rules we follow when writing routes is that as soon as there are two of something, we put it in a route group. Whether it's a shared URL prefix, name, or middleware, once it's repeated, it becomes a group.

The "rule of three" tries to avoid premature abstraction, but because route grouping is so simple, it's a low risk thing to do (or change your mind on later).

I also argue that grouping routes isn't primarily about reducing the lines of code or eliminating duplication. More important to me is that grouping makes your routes more consistent, which makes them easier to read and maintain.

It can also sometimes highlight discrepancies where things are slightly different, but shouldn't be.

Give your route file a quick scan and see if there is room for improvement.

Here to help,

Joel

P.S. How much do you think about security? Check out these 7 steps to a more secure Laravel app.

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.