0

I have a database with 3 tables : users, events and user_event.

I create my event. Once my event is created, I would like to add users.

How can I add him via a form to add users?

My pivot table contain :

event_id, user_id

Do I need to create a UserEventController?

My model relations :

public function users()
{
    return $this->belongsToMany('User')->withPivot('user_event');
}

For create an event :

public function store(Request $request)
{
    $this->validate($request, [
        'course_name'  => 'required|max:255',
        'academic_year' => 'required|max:4|min:4',
        'exam_session' => 'required',
        'date_event' => 'required'
    ]);

    $event = new Event();

    $event->course_name  = $request->course_name;
    $event->academic_year = $request->academic_year;
    $event->exam_session = $request->exam_session;
    $event->date_event = $request->date_event;

    $event->save();
}

Thanks for your help !

Jeremy
  • 1,756
  • 3
  • 21
  • 45

2 Answers2

0

So you need to use the attach()method :

$event->users()->attach($userId);

more informations here : Laravel Eloquent - Attach vs Sync

lovis91
  • 1,988
  • 2
  • 14
  • 24
0

Since the event is already created, you can just use the event object to add an existing user, create a new one, or maybe even sync a list of users.

//create a new user
$event->users()->create(['name' => 'user name', 'email' => 'user email']);

//attach existing user
$event->users()->attach($userId);

//sync multiple existing users passing array of user ids
$event->users()->sync([1,2,4]);

You can see details about all of those methods and a few more here: https://laravel.com/docs/5.7/eloquent-relationships#inserting-and-updating-related-models