For getting every new tutorial link Please join our telegram group

Part 1 laravel eloquent one to one model relationship by hasOne() method with example

In this laravel eloquent we will discuss these problems. How to use one to one relationship, laravel one to one relationship with hindi video tutorial, one to one relationship not working, hasOne relationship in laravel.

Laravel eloquent one to one relationship with example

Laravel one to one relationship use when one table one row relationship with another table by only one row. This relationship return only one row relation data. hasOne() method use in model for define one to one relationship. hasOne() relationship first argument pass related model class name.

This is very basic relationship let we discuss with example. An users table and another is details table both associated with relationship. than we use a detail() method in users table and detail() method contain hasOne() method. Here User and UserDetail are two methods

User Model
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class User extends Model {
    
    public function detail() {
        return $this->hasOne(Detail::class);
    }
}
UserController

this is our UserController where we get relationship data using with() method

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller{
    public function index(){
        $users = User::with('detail')->get();

        foreach($users as $user){
            dd($user->detail); //print first user relation data
	    dd($user->detail->phone); //print detail model phone column data
        }

        or print all users data
        dd($users);
    }
}

Customize hasOne() method

When our table primary key or foreign key column name not follow standard way than customize these name in second and third argument. standared way follow as primary key name have 'id' and foreign key name table singular form underscore id like detail_id.

 return $this->hasOne(Detail::class, 'foreign_key', 'local_key');

hasOne inverse relationship

When we use relationship table and get main table data than it call inverse relationship and use belongsTo() method for define inverse relationship. Now we access User model data by Detail model

Detail model example for hasOne inverse relationship
<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Detail extends Model {
    
    public function user() {
        return $this->belongsTo(User::class);
    }
}

Customize belongsTo() method

When we customize foreign key and primary key name

 return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links