Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AvStar's avatar

Help on how to use one Address model multiple times.

Hi, I am learning Laravel as my lockdown project (beginner) and I've become stuck on the best way to proceed with my current build.

At the moment I have a Users database and an Address database so that users can register multiple addresses. It's set up as a polymorphic many to many relationship and this bit all works fine.

Now I would like to add Football Clubs and hold their addresses in the same database but this where I hit my road block. What's the best, easiest way to do this that can also scale up?

So far I have thought of having a separate FootballClubAddressController but I don't know how to do that without repeating a bunch of code I've already used in the AddressController.

Or maybe I should have one AddressController with some sort of if/then clauses peppered throughout? Again I'm not sure how to that without that also becoming messy.

So if someone could point me towards the best way to do this. that'll be much appreciated.

And just so know, I'd like the method to work not just for addresses, but emails and phone numbers, and won't just be Users and Football Clubs, but also Venues and Offices.

Thanks in Advance.

A

0 likes
3 replies
Snapey's avatar

You've already taken the main step of using a polymorphic relationship.

You should be able to manage all addresses with the one controller, you just need to be passed the related model class and id.

I do this by passing the model to the address controller.

Then use php's get_class() function so that you have the model name as a string, and get the model->id

Once you have these two bits of information, you can add them to the newly created address (or the pivot)

2 likes
AvStar's avatar

Ahh, didn't know about the get_class() function!

So to flesh it out a bit more, I would change my routes to include {model} variable and then add each method in the AddressController would use that. I could then usesomething like a Trait to check which model, if any, is returned, to save repeating my code everywhere?

Please or to participate in this conversation.