How To Use Laravel Eloquent One To One Relationship

2
281
How To Use Laravel One To One Relationship

In this chapter, we will learn how to use laravel eloquent One To One relationship. I am using the latest version of the Laravel Framework which is 6.2. It needs PHP version 7.2.0 or higher. You can easily join tables with laravel eloquent relationships. So let’s get started.

# Requirements

  • Laravel installed in your system. Click Here to know how to install Laravel Framework
  • Composer installed in your system.

If you don’t know about eager loading please learn: How To Use Eager Loading In Laravel

One To One Relationship is a basic relation between two models. Lets take an example with two models Employee and Job. Every employee has one job.

# Create models with migrations

Go to PHP project directory and use the following command to install Employee and Job model and migrations.

php artisan make:model Employee -m
php artisan make:model Job -m

Using -m option will automatically create migration for model in database > migration folder

In Employee model and replace below code.

/* app > Employee.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $fillable = ["name", "email"];
}

Likewise, In Job model and replace below code.

/* app > Job.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    protected $fillable = ["employee_id", "name_of_company"];
}

# Create Database Schema In Migrations

/* database > migrations > *_create_employees_table.php */

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email');                        
        $table->timestamps();
    });
}

Open jobs table migration and replace below code into it

/* database > migrations > *_create_jobs_table.php */

public function up()
{
    Schema::create('jobs', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('employee_id');
        $table->string('name_of_company');       
        $table->timestamps();

        $table->foreign('employee_id')->references('id')->on('employees');
    });
}

Migrate two tables with following command. This will create two tables in database.

php artisan migrate

# Generating dummy data with faker

Its a good practice to create a dummy data. Create EmployeeAndJobSeeder with following command.

php artisan make:seeder EmployeeAndJobSeeder

Above command will automatically create seeder in database > seeds folder.

Update below code in DatabaseSeeder.php.

/* database > seeds > DatabaseSeeder.php */

public function run()
{
    $this->call(EmployeeAndJobSeeder::class);
}

Furthermore in EmployeeAndJobSeeder.php and replace below code. I’m using faker package to generate dummy data. Below code will create 10 records. You generate even more as you want.

/* database > seeds > EmployeeAndJobSeeder.php */

<?php

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Employee;
use App\Job;

class EmployeeAndJobSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        foreach(range(1, 10) as $index)
        {
            $employee = Employee::create([
                'name' => $faker->name,
                'email' => $faker->safeEmail
            ]);

            Job::create([
               'employee_id' => $employee->id,
               'name_of_company' => $faker->company,
            ]);
        }
    }
}

Using below command you will get dummy records in employees and jobs table

php artisan db:seed

# Defining Relationship

Finally, we are ready to define laravel eloquent one to one relationship between Employee and Job models.

First of all, define job function (take any name you want) with hasOne method in Employee Model. Every One To One relation must have hasOne method connected to his related model.

/* app > Employee.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $fillable = ["name", "email"];

    public function job()
    {
        return $this->hasOne('App\Job');
    }
}

Similarly in Job model define employee function (you can take any name you want) with belongsTo method in it. That is inverse relationship.

/* app > Job.php */

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    protected $fillable = ["employee_id", "name_of_company"];

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

Thats It! You created one to one relationship between Employee and Job model. You just need to remember hasOne and belongsTo functions defined in models.

# Usage

Suppose if you have employee object and you want to find job of the employee then you can use hasOne function defined in Employee model.

$employee = App\Employee::find(1);
$employee->job->name_of_company;

 

If you have job object and you want find employee then you can use belongsTo function defined in Job model.

$job = App\Job::find(1);
$job->employee->name;

Please follow following tutorials to know more about Laravel Relationships

2 COMMENTS

  1. This is very helpful for beginners to understand and learn easily because of it follows steps and also highlights points which are important.

LEAVE A REPLY

Please enter your comment!
Please enter your name here