How To Create One to One Model Relationship In Laravel 11 using Example

  Apr 2024
  ITSolutionsGuides
  Category: Laravel

Welcome To ITSolutionsGuides,

In this tutorial we will see How To Create One to One Model Relationship In Laravel 11 using Example. Laravel various eloquent model relationships that are very useful for the artisans. Laravel eloquent are use to create a link like structure between the migration tables and also easily retrieve records from multiple table at once. In this example we will see how to use one to one eloquent model relationship in laravel 11, we will create two migrations users table and phone table in order to store the phone number of the users both the table will be connected using one to one relationship using hasOne() and belongsTo() methods in laravel. Lets step into the example,

Lets Start Coding

Lets create a new project and then lets create two migrations as below,


Users Table

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    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.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Lets Start Coding

while creating the child table migration we need to specify the parent table using the foreign key. In this case our parent table is users table lets create foreign key $table->foreignId('user_id')->constrained('users');


Phone Table

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

Lets Start Coding

In the parent table model we should add the child table model class. Since for each record in the parent table there will be only one record in the child table we should use the ->hasOne() relationship.
app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable
{
    use 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',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * 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);
    }
}

Lets Start Coding

In the child table model we should mention which is the parent table and we should add the parent table model class here, using ->belongsTo()


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

Lets Get Records

Fetching the records from the parent table to the child table,

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

Lets Get Record

Fetching the records from the child table to the parent table,

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

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides