Laravel Eloquent Relationships | Laravel One to One Eloquent Relationship Tutorial

In this tutorial, I would like to explain one to one model relationship in the laravel app. One to One model relationship is very simple and basic. you have to make sure that one of the tables has a key that references the id of the other table. we will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records, etc.

In this example, I will create a “users” table and a “phones” table. both tables are connected with each other. now we will create one to one relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records, and then how to create records too. So you can also see the database table structure below the screen.

One to One Relationship will use “hasOne()” and “belongsTo()” for relation.

Create Migrations

Now we have to create a migration of the “users” and “phones” table. we will also add a foreign key to users table. so let’s create like as below:

users table migration:

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

phones table migration:

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');
});

Create Models

Here, we will create a User and Phone table model. we will also use “hasOne()” and “belongsTo()” for the relationship of both models.

User Model:

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}

Phone Model:

<?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');
}
}

Retrieve Records:

$phone = User::find(1)->phone;
dd($phone);
  • Second Example
$user = Phone::find(1)->user;
dd($user);

Create Records:

$user = User::find(1);
$phone = new Phone;
$phone->phone = '9429343852';
$user->phone()->save($phone);

Second Example

$phone = Phone::find(1);
$user = User::find(10);
$phone->user()->associate($user)->save();

No comments

Note: only a member of this blog may post a comment.