Laravel 10 One to One Relationship Example

By Hardik Savani November 5, 2023 Category : Laravel

Hey Developer,

This is a short guide on laravel 10 one to one relationship example. we will help you to give an example of laravel 10 eloquent one to one relationship. you can see laravel 10 hasone relationship example. This article goes in detailed on laravel 10 belongsto relationship example.

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 the "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 migration of "users" and "phones" table. we will also add foreign key with users table. so let's create like as below:

users table migration:

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up(): void

{

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

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down(): void

{

Schema::dropIfExists('users');

}

};

phones table migration:

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up(): void

{

Schema::create('phones', function (Blueprint $table) {

$table->id();

$table->foreignId('user_id')->constrained('users');

$table->string('phone');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down(): void

{

Schema::dropIfExists('phones');

}

};

Create Models:

Here, we will create User and Phone table model. we will also use "hasOne()" and "belongsTo()" for relationship of both model.

app/Models/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;

use Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable

{

use HasApiTokens, HasFactory, Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name',

'email',

'password',

];

/**

* The attributes that should be hidden for serialization.

*

* @var array

*/

protected $hidden = [

'password',

'remember_token',

];

/**

* The attributes that should be cast.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

/**

* Get the phone associated with the user.

*

* Syntax: return $this->hasOne(Phone::class, 'foreign_key', 'local_key');

*

* Example: return $this->hasOne(Phone::class, 'user_id', 'id');

*/

public function phone(): HasOne

{

return $this->hasOne(Phone::class);

}

}

app/Models/Phone.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Phone extends Model

{

use HasFactory;

/**

* Get the user that owns the phone.

*

* Syntax: return $this->belongsTo(User::class, 'foreign_key', 'owner_key');

*

* Example: return $this->belongsTo(User::class, 'user_id', 'id');

*/

public function user(): BelongsTo

{

return $this->belongsTo(User::class);

}

}

Retrieve Records:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

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

dd($phone);

}

}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Phone;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

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

dd($user);

}

}

Create Records:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use App\Models\Phone;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$user = User::find(1);

$phone = new Phone;

$phone->phone = '9429343852';

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

}

}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use App\Models\Phone;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$phone = Phone::find(1);

$user = User::find(10);

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

}

}

I hope you understand of one to one relationship...

Shares