Dealing with name collision in different namespaces

Optimize for simplicity

Joel Clermont
Joel Clermont

Before I get into my approach for dealing with name collisions, my first bit of advice is to just try to avoid them in the first place. Usually an extra thought or two when picking a name can avoid the problem altogether.

But let's assume you have a collision you can't solve by changing a name. How can you handle this in a simple, consistent way in your project?

Consider an example where you have both App\Enums\Client and Apps\Models\Client.

My general rule is that the model "wins", by which I mean that I import that one so I can just say Client in code and it points to the model. My reason is that models tend to be used most frequently. And even if there are cases where that doesn't hold true, it's a consistent pattern which is easy to follow.

Next, you have to decide how to refer to the "losing" class. One option is to fully qualify it as App\Enums\Client every time you use it. This is fine for short namespaces but it can get pretty verbose.

Another option is to import just enough of the namespace to distinguish it. For example if I import App\Enums I can then refer to Enums\Client. This works well even with long namespaces.

My favorite option, however, is to use an import alias. If my import statement is use App\Enums\Client as ClientEnum then I can just refer to ClientEnum in my code without having to change the actual enum name. Short and simple.

The main thing is to pick an approach and be consistent. In the end, a good IDE/editor will make it easy to quickly hover or navigate on a class name if anything is unclear.

Here to help,


P.S. Ever have a giant class with no tests, but you need to make a change? Watch me demo an interesting approach on how to do this safely with fuzz testing on a live community call tomorrow. Just one of the perks of the Mastering Laravel community.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.