[FIXED] How to Insert multiple data to one row as students to one class_room in Laravel?


I am working a E-learning website.
I made students, teachers, courses and class_rooms tables in my database.

The plan is to enter a classroom from dashboard then make a new classroom connected to 1 teacher, 1 course and many students.

I can insert teacher and course by ID , but what about the students?
I tried but failed to make another table and connect everything.


You should create pivot table kind
class_room_student. Here you will store class_room ID and student ID.
And use relation many to many

 * In ClassRoom Model (getting students of class)
public function students()
    return $this->belongsToMany(Student::class);

 * In Student Model (getting classes of one student)
public function classes()
    return $this->belongsToMany(ClassRoom::class);

Don’t forget about ‘pivot table’, ‘foreign_key’, ‘other_key’ if needed.


public function up()
    Schema::create('class_room_student', function (Blueprint $table) {


        $table->primary(['student_id', 'class_room_id']);

public function down()

Answered By – Yurich

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published