what is one to one relationship in laravel?

A one-to-one relationship is a very basic relation.

two tables called users and mobile.


Step 1 : Create Migration and Model

We have already the User model and migration file. Let’s create a model named Mobile with a migration file. Run this command to create both:

php artisan make:model Mobile -m

Now open the migration file for the Mobile model from database>migrations directory.

File name : create_mobiles_table.php

public function up()
{
Schema::create('mobiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('mobile');
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});
}

We have set user_id as a foreign key and mobile number will be deleted if we delete the user.


Step 2 : Setup One To One Relationship

We have two models User & Mobile. For example, a User model might be associated with one Mobile. To define this relationship, we place a mobile method on the User model. The mobile method should call the hasOne method and return its result.

File name : app/User.php

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
// ...

/**
* Get the mobile number associated with the user.
*/
public function mobile()
{
return $this->hasOne(Mobile::class);
// note: we can also inlcude Mobile model like: 'App\Mobile'
}
}

Step 3 : Inverse Of The Relationship

So, we can access the Mobile model from our User. Now, let’s define a relationship on the Mobile model that will let us access the User that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method.

Open Mobile model and paste this code:

File name : app/User.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mobile extends Model
{
/**
* Get the user that owns the mobile.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}

Step 4 : Insert Records

File name : UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use App\Mobile;
use Hash;

class UserController extends Controller
{
public function addUserMobile()
{
$user = new User;
$user->name = "Test Name";
$user->email = "test@mnp.com";
$user->password = Hash::make("12345678");
$user->save();

$mobile = new Mobile;
$mobile->mobile = '123456789';
$user->mobile()->save($mobile);
}
}

Step 5 : Retrieve Records

File name :

public function index()
{
// get user and mobile data from User model
$user = User::find(1);
var_dump($user->name);
var_dump($user->mobile->mobile);

// get user data from Mobile model
$user = Mobile::find(1)->user;
dd($user);

// get mobile number from User model
$mobile = User::find(1)->mobile;
dd($mobile);
}

Step 6: Update Records

File name :

public function update()
{
$user = User::find(1);

$user->name = 'Test II';
$user->mobile->mobile = '987654321';
$user->push();
}

Step 7 : Delete Records

File name :

public function delete()
{
$user = User::find(1);
$user->delete();
}

File name :


Example :-

File name :


Example :- One-to-one Relationship

users table migration:

File name :

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:

File name :

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

});

User Model:

File name : 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

File name :

<?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:

File name :

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

Create Records:

File name :

$user = User::find(1);

$phone = new Phone;
$phone->phone = '9429343852';

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

File name :

$phone = Phone::find(1);

$user = User::find(10);

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





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial