Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Use hasOne Relationship in Laravel

How to Use hasOne Relationship in Laravel with Example ?

Aman Jain, February 27, 2022October 4, 2022

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.


Database Relations are used to create the relations between the tables so that we can manage the transactions in a better way. Similar to database relations laravel itself provides relationships out of the box to create the relation between tables in the application layer.

Laravel relations do not create relations in database it creates relation in application layer and produces the output.

Laravel eloquent hasOne accepts 3 parameters first as model name, second is optional foreign_key and third is optional local_key .

Here is the syntax

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Owner extends Model
{
     
    public function child()
    {
        return $this->hasOne(child::class,'foreign_key','local_key');
    }
}

In the above syntax we have used belongsTo method with 3 parameters so here Child::class is the name of Model which we want to relate, foreign_key means column name of child table and local_key means column name of own table.

Laravel do not create join query internally but it creates a separate query and then attach the data.

So we can use it as below:

Article::with('child')->get();

This will return all the articles along with first comment.

Let’s understand laravel hasOne in eloquent query with example

Use of hasOne to method in article comments table

Suppose we have two tables one is article and another one is comments so comments table contains comments of articles table so here is the schema of both tables and you can also read How to make database connection in Laravel 8 ?

Screenshot 2022 02 27 at 10.53.34 AM
Articles table
Screenshot 2022 02 27 at 10.55.01 AM
Comments table

Step 1 : Create article and comment model

Create two model in app\Models folder, one is article and other is comment

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;
}

Comment Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;
}

Step 2 : Create hasOne relation in Article model

Now create hasOne relation in Article class so that we can fetch comment detail using article_id

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;

    public function comment(){
        return $this->hasOne(Comment::class);
    }
}

In the above code we have created a method comment and used hasOne method to create the relation with Comment Model.

Laravel assumes here table name is comment and foreign key is comments table article_id and local key is articles table id. If you have different columns name to map then you can change.

Step 3 : Use the relationship in controller

We have created the relation now we need to access the model and its relations so lets create a controller and import the necessary classes

<?php

namespace App\Http\Controllers;

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


class ArticleController extends Controller
{

    public function index(Request $request)
    {

        $article=Article::with("comment")->first();
        dump($article);

        dump($article->comment);

    }
}

Step 4 : Create Route

Lastly create the route in web.php

Route::get('/articles',[ArticleController::class, 'index']); 

How to get last row relation in hasOne relation ?

Sometime we wanted to get last row in hasOne relation so then we can use oldestOfMany method


public function comment(){
        return $this->hasOne(Comment::class)-> oldestOfMany();
}

How to get last first relation in hasOne relation ?

Sometime we wanted to get first row in hasOne relation so then we can use lastestOfMany method


public function comment(){
        return $this->hasOne(Comment::class)->lastestOfMany();
}

Related

Php Laravel hasOnelaravelmysqlrelation

Post navigation

Previous post
Next post

Related Posts

Php How to convert html to pdf in laravel 8 9

How to convert html to pdf in laravel 8 / 9?

May 5, 2022November 6, 2023

Dompdf package has rich features to convert html to PDF in laravel. In this article we will learn to use html to PDF using dompdf package. In most of the website there is need of to convert html to PDF or export the data in PDF format, Dompdf does this…

Read More
Php laravel multiple where condition in eloquent

How to use laravel multiple where condition with example ?

March 5, 2022November 8, 2023

In this article i will show you to use laravel multiple where condition in eloquent. In laravel we can create multiple where condition in several ways like using the array of array, associative column and value and using multiple where clause. Sometimes we wanted to use multiple and condition or…

Read More
Php Laravel password hash and check

How to create hash password in laravel 8 ?

January 26, 2022January 26, 2022

Laravel provides robust security features and one of them are hash password which is not decryptable. For hashing the password laravel use secure Bcrypt and Argon2 hashing for storing user passwords. Password encrypted with Bcrypt can not be decrypt since it uses key to generate the hashed string and irreversible…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version