OneToOne , OneToMany , HasMany and HasOne relationship in laravel 9

OneToOne , OneToMany , HasMany and HasOne relationship in laravel 9

01-Oct-2022
| |
Image Carousel

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 . 

So starting with creating model and migration Copy

php artisan make:model UserContacts -m

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.phpCopy

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

Here we define our user_id as foreign key with refrence to users table. Now  hit php artisan migrate in terminal Copy

php artisan migrate

 After that we will create some dummy data in UserContacts . In any controller create some dummy data and call this function . 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 .

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

In app/Models/User.php paste the following code in User 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 .

 

If you have different foriegn key in table just define it there along with auto-increment key.

Now call this function in any controller Copy

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

Call thiis function by any controller..Result we get .

 

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

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

 

For BelongsToMany Relationship you may consider developer-corner.vm-services.tech/developer-corner/post/1662920799/make+user-roles+by+using+eloquent+method+with+pivot-table+in+laravel

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,
Related Articles
Load More

Newsletter