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

latz's avatar
Level 3

Create new row and sync many to many relationship

I would like to schedule appointments with my application. I want to capture the participants. There are three tables: student, event and student_event.

My wish: I create an event and assign the participating students in one step.

If i know the id from the event table, this code works:

$id = 3;
$event =  Event::findOrFail($id);
$event->students()->sync($request->id);

How can I create a new event record and then assign the participants?

My form looks like (filled):

Event:   "2019-02-01"
Student A: x
Student B: -
Student C: -
Student D: x
Student E: x
Submit
0 likes
2 replies
JohnBraun's avatar
Level 33

Assuming that $request->id is an array of user id's of participating students, is this what you want to do?


$event = Event::create(); // pass in all the parameters necessary for the creation of a new event

$event->students()->sync($request->id);

1 like
latz's avatar
Level 3

Many thanks for your solution. It works.

Please or to participate in this conversation.