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

Mephisto's avatar

Laravel belongstomany with pivot - save one row at a time

Help me correct this query/code for saving/attaching one row at a time when Im adding a subject to a student. I have 3 links. create student, create subject, and adding subject to student. when i add 1 subject to 1 student, it saves all subjects and students on my student_subject table. I just want to save 1 at a time based on what I added. TYIA.

public function storeStudentSubject()
    {
        //add subject to student
        foreach(Student::all() as $student) {
            $subjects = Subject::all()->pluck('id');
            $student->subjects()->attach($subjects);
        }

        // redirect to index
        return redirect('/dashboard');
    }
0 likes
2 replies
SilenceBringer's avatar

Hi @mephisto really not understand you question. Here

foreach(Student::all() as $student) {

you ger all the students, and here

$subjects = Subject::all()->pluck('id');

you get all the subjects, and then

$student->subjects()->attach($subjects);

attach all the subjects step by step to every student. So, in total, of course, all students have all subjects.

you need to specify The exact student and exact subject you want to attach, like

Students::first()->subjects(Subject::first()->id);

this example will attach first subject to first user. Or if you have specified student id and subject id

Student::find($sudentId)->subjects()->attach(Subject::find($subjectId)->id);
Mephisto's avatar

Thankyou for your response. For example, on my database i have student1 and student2 on students table. and subject1 and subject2 on subjects table. On my student_subject pivot table its empty. Now, I want to add subject1 to student1. What code should I use to pass the id of selected student1 and subject1 to student_subject table? If i use the code mention above it just saves all the id. I think i have a mistake on using foreach and all() query. can you help me fix this. thankyou

Please or to participate in this conversation.