Laravel Eloquent HasOne relationship ( one to one ) - Explained

How to use HasOne relationship in Laravel Eloquent

Laravel Eloquent HasOne relationship ( one to one ) - Explained

Laravel is one of the best frameworks among all the php frameworks due to its lots of features and inbuilt functionalities which makes our development more faster and effiecient and one of these best feature is Eloquent.

Eloquent provides us the mechanism to deal with multiple table joins in a very easy and efficient manner by handling the complexity at its own end. Eloquent provides lots of relationship models line one to one, one to many and many to many etc.

In this article we will be fully focusing on One to One relationship that is HasOne relationship with Example.

What it One to One Relationship ( hasOne ) :

One to One relationship is type of database operation where we are connecting two tables records with each other with a foreign key. Let's take an example for better understanding, Suppose we have 2 table one is users and another is posts table.

Let's assume that a user can have only one post. So now we have two tables users and posts, and we need to connect these two tables. so to achieve this we have to store a foreign key at posts table ( user_id ) for connecting posts table with users table. Now let's see this with the example.

Table structure of users table:

Laravel Eloquent HasOne relationship ( one to one ) - Explained

Table structure of posts table:


Laravel Eloquent HasOne relationship ( one to one ) - Explained

Now we have our two tables and we need to perform one to one relationship. First we need to create two models for these two table. You can use the following command to create your models.

php artisan make:model User

User Model:


<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function getPost(){
        return $this->hasOne(Post::class,'user_id','id');
    }
}

Post Model:


<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;
    public function getUser(){
        return $this->belongsTo(User::class,'id','user_id');
    }
}

Create a route:


Route::get('getusers',[HomeController::class,'getUsers'])->name('users.getusers');

Code on Controller:


<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    public function getUsers(){
        try{
            $users = User::with('getPost')->get();
            return $users;
        }catch(\Exception $e){
            return false;
        }
    }
}

Output:


Laravel Eloquent HasOne relationship ( one to one ) - Explained


Previous Post Next Post

Contact Form