OneToOne , OneToMany , HasMany and HasOne relationship in laravel 9

OneToOne , OneToMany , HasMany and HasOne relationship in laravel 9

14-Sep-2024
| |
Image Carousel

Table of Contents

S.no Contents-topics
1 Introduction
2 Creating model & migration
3 Configuration of migartion file
4 Creating user data
5 Creating relations in model
6 Condition based relationship

1:Introduction

In our old school we majorly uses query builder like join ( inner join , left join )   to find a relation of single id in many table or using RDBMS(Relationship based Database Management System) its very important to when you are working on a project where single id  has relations in many tables . For eg - we have a table users and a table name user_contacts , to get user corressponding address we may use join or left join but we have different option which is known as ORM Relaionship . ORM Relationship are good practice when you are working on a big project as to make the length of the code short and easy to understand.

2:Creating model & migration

So starting with creating model and migration hit the below command in the terminal and it will create a model and corresponding migration in your laravel application
command for model:
 Copy

php artisan make:model UserContacts -m

3:Configuration of migartion file

This wil crreate a model app/Models/UserContacts and a migration file now paste the following code in migration file database/migrations/xxxx_create_user_contacts_table.php . As you can see in the below code we are using  $table->unsignedBigInteger('user_id)->nullable()  and in the bottom of the code $table->foreign('user_id')->refrence('id')->on('users')->onDelete('cascade') as this will create a foreign key refrence of users table id in user_contacts table with the name user_id as shown below.
code for migration:
 Copy

<?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('user_contacts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->nullable();
            $table->string('full_address')->nullalbe();
            $table->timestamps();
           
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
 
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_contacts');
    }
};

Now hit php artisan migrate to create a migration in database
command for migrate: 
Copy

php artisan migrate

4:Creating user data

After that we will create some dummy data in UserContacts . In any controller create some dummy data and call this function as we are creating data in user_contacts table as example , this function createDeveloper()  will create a new user and id of this user will save in user_contacts making user_id as foreign key. Copy

 public function createDeveloper()
    {
        $user           =    new User();
        $user->name     =    'Developer';
        $user->email    =    '[email protected]';
        $user->password =     Hash::make('1234');
        $user->save();
 
        for($i=0;$i<5;$i++){
            $address                =   new UserContacts();
            $address->full_address  =   'https://developer-corner.vm-services.tech/developer-corner/';
            $address->user_id       =   $user->id;
            $address->save();
        }
     
    }

Now we have many address that belongs to single user (user_id = 109).

As seen user_id 109 hasMay addresses in user_contacts table now we call this addresss by relationship.

5:Creating relations in model

In app/Models/User.php we are creating hasOne(one to one) relation and hasMany(one to many) relation , if you are having different foreign key then you may define your foreign key under the relationship class as shown in manyContact() function .
code for model:
Copy

  public function singleContact()
    {
         return $this->hasOne(UserContacts::class,);
    }
 
    public function manyContact()
    {
         return $this->hasMany(UserContacts::class,'user_id','id');
    }

 so basically we have two functions here singleContact = hasOne and manyContact=hasMany relationship .

 

Now call this function in any controller using with statement as shown in below code we are fetching data from both the functions to show the difference between OneToOne and OneToMany in OneToOne it only sends single array whereas in OneToMany it sends all the contacts under many_contact array
code for controller:
 Copy

  public function getUserAddress()
    {
        $user      =   User::with('singleContact','manyContact')->get()->toArray();
        echo"<pre>"; print_r($user);die();
    }

Result we get .

 

6:Condition based relationship

If you want add any condition like orderBy clause or any clause or whrere condition do it in this way 
code:Copy

  public function singleContact()
    {
         return $this->hasOne(UserContacts::class,)->orderBy('id','desc');
    }

 

Tags: hasMany and hasOne relationship in laravel 9 , laravel relation , how to make relationship in laravel 9,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter