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

geekshubh's avatar

Adding data into pivot table

I have three tables, "classroom", "users", "classroom_user"(pivot table). Now what I need to do in the form that I want is that I want to enter the title, and then have a multiple select field where I can select many users, once I hit submit, the "ids" must be saved in the pivot table as "teacher_id"(foreign key for id in users table). How do I set up my controller and also the vue component? Thanks in advance!

0 likes
3 replies
burlresearch's avatar
Level 40

This is a bit of an open-ended question. Your Vue component could look like this for the select:

// TEMPLATE
        <div class="form-group">
          <label for="selectTeachers">Select multiple Teachers</label>
          <select v-model="formdata.teachers" multiple class="form-control" id="selectTeachers">
            <option v-for="teacher in teachers" :value="teacher.id" v-text="teacher.name"></option>
          </select>
        </div>
        teacher ids: {{formdata.teachers}}

// SCRIPT
    data() {
      return {
        teachers: [
          {id: 1, name: 'Aristotle'},
          {id: 2, name: 'Einstein'},
          {id: 3, name: 'Confucius'},
          {id: 4, name: 'Twain'},
          {id: 5, name: 'Kamvar'},
        ],
      };
    },

As for your Controller, who knows, why don't you post what you have. But,

We expect you would POST somehow the this.formdata from your component, so in your Controller::store() you would have a line like:

  $classroom->teachers()->sync($request->teachers);
geekshubh's avatar

Okay I got the select component loaded with teacher ids, now the question is how do I save these ids into the pivot table? Can you help me with controller and vue component?

Here is my current vue component and controller file:- https://jsfiddle.net/g1ejpoan/

Please or to participate in this conversation.