Site icon FahmidasClassroom

How to create one-to-many relation in database using Laravel

Laravel Relationship

Applying one-to-many relationship in the database using Laravel

Steps
1. Create a migration file for adding a new table students

php artisan make:migration create_table_students

2. Add the following code in the up function


Schema::create('students', function(Blueprint $table)
{
$table->integer('id')->primary();
$table->string('name');
$table->text('email');
$table->string('course');
$table->boolean('done')->default(false);
$table->timestamps();
});

3. Create a migration file for adding a new table subjects

php artisan make:migration create_table_subjects

4. Add the following code in the up function

Schema::create('subjects', function(Blueprint $table)
{
    $table->integer('module');
    $table->integer('student_id');
    $table->foreign('student_id')->unsigned()->references('id')->on('students')->onDelete('cascade');
    $table->text('subject_name');
    $table->primary(array('module','student_id'));
    $table->timestamps();
});

5. Add Student and Subject Model

php artisan make:model Student
php artisan make:model Subject

6. Run the migrate command

php artisan migrate

7. To define one-to-many relationship,

Edit the Student model and add the following code

public function subjects()
{
     return $this->hasMany('todoparrot\Subject');
}

8. Add the following code in Subject model

public function students()
{
      return $this->belongsTo('todoparrot\Student');
}

9. Add the following code in the SubjectController,

use todoparrot\Student;
use todoparrot\Subject;
public function index()
{
    $list = Student::find(1);
    $sub = new Subject;
    $sub->module = 103;
    $sub->student_id = 01;
    $sub->subject_name = 'PHP';
    $list->subjects()->save($sub);
    $sub = new Subject;
    $sub->module = 104;
    $sub->student_id = 01;
    $sub->subject_name = 'AngularJS';
    $list->subjects()->save($sub);
     
}

10. Add a record in students table and add the following code in the controller

public function show($id)
{
    $list = Student::find($id);
    return view('show')->with('list', $list);
}

11. Add route to call index and show method.

12. Create a new view file under named show.blade.php

13. Add the following code in the view file


<h2> Student ID: {{ $list->student_id }} <br /> Student Name: {{ $list->name }} </h2>
<h3> Subjects </h3>
@if ($list->subjects->count() > 0)
@foreach ($list->subjects as $subject)
<li>{{ $subject->subject_name }} </li>
@endforeach
@else
No subject is assigned for this student
@endif

The steps are shown in the following video tutorial.

Good Luck

Exit mobile version