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..
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
@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.
Please or to participate in this conversation.