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

Issue

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.

Solution

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.

Migration

public function up()
{
    Schema::create('class_room_student', function (Blueprint $table) {
        $table->integer('student_id')->unsigned();
        $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');

        $table->integer('class_room_id')->unsigned();
        $table->foreign('class_room_id')->references('id')->on('class_rooms')->onDelete('cascade');

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

public function down()
{
    Schema::dropIfExists('class_room_student');
}

Answered By – Yurich

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published