Laravel Eloquent One to One (hasOne) Relation Example Tutorial

laravel one to one relationship example; In this tutorial we will are going to explain how to use one to one (hasOne & belongsTo) eloquent model query relation in laravel application.

A one-to-one relationship is a very basic relation. When one table refers to single row in another table that is called a one-to-one relationship. There should only be one matching record found in another table where you have one-to-one relationship defined.

Follow the following steps to use one to one Eloquent relations in laravel application.

Step 1: Install Laravel

Install and configure the basic configuration of laravel application.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Model & Migrations

After the first installation we have already created user model and users migration so only need to create a Phone Model and migration for running the following command:

php artisan make:model Phone -m

Our users table migration look like this.

users table migration:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Now here we need to update our phones tables here just like below, we add the user_id in our phone migration with goreign key.

phones table migration:

public function up()
{
    Schema::create('phones', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('phone');
        $table->timestamps();
    
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

Run the php artisan migrate command to generate tables in database.

Step 3 : One To One Relationship

We have two models User & Phone let’s see how we use hasOne and belongsTo to both models.

the hasOne method generally add in parent table, So here our parent table is users note this its work your avery time. In Parent Table we use hasOne for getting one to one relation. Below the user model look like:

app/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

If you are getting the user using phone model then here we use belongsTo Relation in Phone Model. In child table model we use belongsTo note this line. If you are geeting phone and want to get the owner of phone then you must use belongsTo here just like below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Step 4: Retrieve Records

Here we are geetings users so we easily get there phone just like below.

public function index()
{
    $userPhone = User::find(1)->phone;
    dd($userPhone);
}

If you are geeting phone and want to get the owner of phone then you must use belongsTo here just like below:

public function index()
{
    $user = Phone::find(1)->user;
    dd($user);
}

Gettings multiple users with their phone model then we need to add with for it just like this code and we can use in blade files as well.

public function index()
{
    $users = User::with('phone')->get();
     
    dd($users);
}

Step 5: Create Records

public function store()
{
    $user = User::find(1);
    $phone = new Phone;
    $phone->phone = '9429343852';

    $user->phone()->save($phone);
}

We can store the data parent and child tables just like below.

public function store()
{
    $phone = Phone::find(1);
    $user = User::find(10);
     
    $phone->user()->associate($user)->save();
}

Read Also: Laravel One to Many Eloquent Relationship Tutorial

So, the laravel one to one relationship tutorial example is over now. I hope you enjoy with this tutorial.

1 thought on “Laravel Eloquent One to One (hasOne) Relation Example Tutorial”

Leave a Comment