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

jammy-git's avatar

Organising controllers and models for creating records that can be related to two other models

I'm getting to grips with the basics of Laravel after moving from another framework and wondered how the best way to organise this code would be...

I have a Contact model. A Contact record can belong to two other models (Schools and Students). I have set up the relationships just fine, but the main thing I was wondering was about controllers and creating and editing records.

Depending upon which model the user is creating a record against should I have just a ContactsController with a different method for creating contacts related to each of School/Student?

Or maybe one method in ContactsController that looks to see which foreign_id key is present and then saves the Contact against the appropriate model?

Or a SchoolContactsController and StudentContactsController?

Or maybe the logic should be in the School/Student models as an addContact method? But again - which controller to call that method from?

0 likes
5 replies
shez1983's avatar

Or a SchoolContactsController and StudentContactsController? is what i would opt for..in which case yur functions in those file will be simply index() create().. etc instead of

something complicated if you decide to go for ContactsController..

jammy-git's avatar

Thanks. I guess from those controllers I would then call a method on each of the School/Student models called addContact?

shez1983's avatar

no you will have a create function in each controller and pass in school id which you can use eloquent to get the model and then save the contacts details..

1 like
martinbean's avatar
Level 80

@jammy-git You have two “nested” resources: a school contact and a student contact. Therefore, I’d create two separate controllers (SchoolContactController and StudentContactController) but look at opportunities to DRY the code.

With relationships set up properly, adding a contact should look like $school->contacts()->create($request->all()). Similarly, $student->contact()->create($request->all()) for a student. You could move this to a synchronous job and pass the parent model and the validated data as constructor parameters, but that may be a bit overkill.

The second opportunity to DRY your code out would be the view. You could use the same view for both creating a school contact and a student contact, as I’m assuming they’d have the same fields. The only thing that would be different is the URL those forms would post to. As aforementioned, the fields (and therefore validation) would be the same across both.

jammy-git's avatar

Thanks to the both of you. I've also just seen the documentation about polymorphic relationships in the Laravel docs that helped to answer a few other questions I had!

Please or to participate in this conversation.