Creating a One to Many Relation in Laravel 5


Creating a Has Many Relation in Laravel 5 Database One-to-Many (also known as the Has Many) relationship occurs when there is a row in a parent db table that corresponds to many raw in a child table.For instance an employee can have multiple attendance records, therefore one employee is related to many attendance entries, meaning we'll need to relate the Employee and Attendance models using a One-to-Many relation. This relationship type is used throughout Laratime Demo Project, so in this section we'll dig deeper at some actual code used to power the system. Continue to Read to learn how this is implemented.

In this post I am not going to show you how to create Database Table Migration or How to Create Model, If you want to learn about how to Create a Database Table by Laravel Migration and its associated models, Please follow my previous article in the following links for related topics, 

An insight to Laravel Eloquent ORM

Creating Foreign Key References in Laravel Migration


I have already created and placed the Employee and Attendance Models in app Folder. Please find the following code for my Employee and Attendance Models.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $table = 'employees';
    protected $primaryKey = 'id';
    protected $fillable = ['id','name','email','telephone','gender','join_date'];
    protected $dates = ['deleted_at'];   
}


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attendance extends Model
{
    protected $table = 'attendance';
    protected $primaryKey = 'id';
    protected $fillable = ['id','empId','inorout','remarks','attendance_date','attendance_time','location'];
    protected $dates = ['deleted_at','attendance_date'];
}

Notice we have included an integer-based column named empId in the attendance table which is a foreign key. In doing so, Laravel will ensure that the column is indexed, and additionally you'll optionally be able to determine what happens to these records should the parent be updated or deleted, to which employee the attendance records are belongs to.

Defining the One to Many Relation

With the Attendance model and underlying table in place, it's time to create the relation. Open the Employee model and create a public method named attendances, inside it referencing the hasMany method as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    ...

    public function attendances()
    {
        return $this->hasMany('App\Attendance','empId','id');
    }

}

Defining the Inverse of the One to Many Relation

You'll likely also want to define the opposite side of the relation within the Attendance model using the belongsTo method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attendance extends Model
{
    ...

    public function employee()
    {
        return $this->belongsTo('App\Employee','empId','id');
    }

}

If you don't understand why we'd want to use the belongsTo relation here, please refer back to the earlier section, "Introducing to Laravel Belongs To Relation".
With the relationships in defined, let's next review how to associate attendance with an employee.

Associating an Attendance Record with Employee Model

To assign an attendance record to an employee, you'll first create a new Attendance object and then save it through the Employee object, as demonstrated here:

$john = Employee::find(245);
$attendance = new Attendance();
$attendance->inorout = 0;
$attendance->remarks = 'Start';
$attendance->attendance_date = '2018-06-15';
$attendance->attendance_time = '08:00';
$attendance->location = 'Office';

$john->attendances()->save($attendance);

$attendance = new Attendance();
$attendance->inorout = 1;
$attendance->remarks = 'End';
$attendance->attendance_date = '2018-06-15';
$attendance->attendance_time = '17:00';
$attendance->location = 'Office';
$john->attendances()->save($attendance);

With two attendance records saved, you can now iterate over the employee's attendance records within a view like you would any other collection. Let's modify the Employee controller's show action/view to additionally display attendance data.

public function show($id)  
{
  $employee = Employee::find($id);    
  return view('employees.show')->with('employee', $employee);
}

We'll only need to create the view (resources/views/employees/show.blade.php) to iterate over the attendance. I'll present the view here:

@extends('layouts.master') 

@section('content')

<h1>{{ $employee->name }}</h1> 

<p>
Created on: {{ $employee->created_at }} 
Last modified: {{ $employee->updated_at }}<br />
</p>

<p>
{{ $employee->join_date }}
</p>

<h2>Attendances</h2>

@if ($employee->attendances->count() > 0)
  <ul>
  @foreach ($employee->attendances as $attendance)

    <li>{{ $attendance->attendance_date.' '.$attendance->attendance_time }}</li>

  @endforeach
  </ul>
@else
 <p>
    There are no attendance records.
</p>  
@endif

@endsection

Filtering Related Records in Laravel One to Many Relation

You'll often wish to retrieve a filtered collection of related records. For instance you might want to get an employee's attendancerecords filtered by an specific date:

$employeeAttendance = Employee::find(1)->attendances()->where('attendance_date', '2018-06-10')->get();


If you have any other questions, experience or insights on "Creating a One to Many Relation in Laravel 5" please feel free to leave your thoughts in the comments bellow which might be helpful to someone!

Written by Akram Wahid 6 years ago

are you looking for a chief cook who can well craft laravel and vuejs, to make some awsome butterscotch,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}