How to Define one-to-one Relationship in Laravel 9?

Mar 24, 2022 . Admin

Hi friends,

Today, I am exaplian How to define one-to-one relationship in laravel 9. In this Laravel one to one relationship example tutorial, I’ll show you to implement one to one relationships In laravel 9 eloquent model. You will also learn how to create and use one to many relationship in laravel 9. One to One model relationship is very simple and basic. When one table refers to single row in another table that is called a one-to-one relationship. This tutorial will see how the One To One Relationship in Laravel 9 is working with an example.

In this example we will learn to implement and use one to one relationship in laravel 9. We will also show you how to insert, retrieve, update, and delete data with the eloquent model from the database table in laravel 9.

Eloquent relationships are defined as methods on your Eloquent model classes. Inside this article we will see the concept of laravel 9 One to One Eloquent relationship as well as we will implement inverse of one to one relationship i.e belongs to.

So let's start following example:

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: 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:

database/migration/2022_3_24_000000_create_users_table.php
<?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()
    {
        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()
    {
        Schema::dropIfExists('users');
    }
};
    php artisan make:migration create_phones_table
database/migration/2022_3_24_000000_create_phones_table.php
<?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()
    {
        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()
    {
        Schema::dropIfExists('phones');
    }
};
Step 3: 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;
  
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()
    {
        return $this->hasOne(Phone::class);
    }
}
php artisan make:model Phone
app/Models/Phone.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Phone extends Model
{
    use HasFactory;
  
    /**
     * Get the user that owns the phone.
     * 
     * Syntax: return $this->belongsTo(Phone::class, 'foreign_key', 'owner_key');
     *
     * Example: return $this->belongsTo(Phone::class, 'user_id', 'id');        
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
Step 4: 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);
    }
}
Step 5: 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...
#Laravel 9