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 !

6
  • add your model relations Commented Jan 17, 2019 at 18:56
  • @LouisR it's done! Commented Jan 17, 2019 at 18:57
  • post your code for adding an event Commented Jan 17, 2019 at 18:59
  • I don't add an event, I want to add a user to the already created event. That's why I'm stuck. Commented Jan 17, 2019 at 19:01
  • post your code i can't help if you don't ;) Commented Jan 17, 2019 at 19:02

2 Answers 2

0

So you need to use the attach()method :

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

more informations here : Laravel Eloquent - Attach vs Sync

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.