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

espamer's avatar

Adding a many-to-many relationship befor triggering model events

Hi! I'm working on adding webhooks to my system and I found this issue.

I have a many-to-many relationship between courses and students. Whenever a new course is created or updated, a webhook is triggered using eloquent model events. This is currently working. Now, I'm trying to do the same but with students.

If a student enrolls in a course, the webhook is triggered the same way, using a pivot model and eloquent model events. This is working too. The problem I have is that, while you can create students independently of any course, you can also create them for a specific course. So what I'm trying to do is, anytime a new student is created for a course, it should trigger a webhook that notifies whoever is listening to the course webhook.

This gives me an egg-and-chicken problem. If I send the webhook when the student is created, the course relationship has not been created yet so I can not check which courses to notify. And I cant create the relationship first because I need a student id to create it.

I've already tried doing something like $course->students()->create($sstudent_data) but the relationship is still being created AFTER the student has been created and the model events triggered.

Is there any way I can tell laravel to trigger the events after the relationship has been created?

0 likes
1 reply
martinbean's avatar

@espamer I’m not really sure I follow and understand the problem. I can see two events where you would dispatch a webhook:

  1. Student is created (so send a student.created event).
  2. Student is enrolled on a course (send a student.enrolled-on-course event to those listening to that course’s webhooks)

Please or to participate in this conversation.