Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
laravel belongsTo

How to Use Laravel belongsTo Relationship in with Example ?

Aman Jain, February 27, 2022November 10, 2023

Laravel BelongsTo relationship is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.


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.

Understand laravel belongsTo Relation

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

Here is the syntax

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

In the above syntax we have used belongsTo method with 3 parameters so here Parent::class is the name of Model which we want to relate, foreign_key means column name of related table and owner_key means column name of self 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:

Owner::with('parent')->get();

This will return all the owner along with parent details.

Let’s understand laravel belongsTo in eloquent query with example

Use of Belongs to method in users and profile table

Suppose we have two tables one is users and another one is profiles so profiles table contains profiles of user 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 11.45.25 AM
User table
Screenshot 2022 02 27 at 11.45.12 AM
Porfile table

Step 1 : Create User and Profile model

Create two model in app\Models folder, one is users and other is profile

<?php

namespace App\Models;

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

class User extends Model
{
    use HasFactory;
}

Profile Model:

<?php

namespace App\Models;

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

class Profile extends Model
{
    use HasFactory;
}

Step 2 : Create belongTo relation in profile model

Now create belongs to relation in profiles table so that we can fetch user detail using user_id

<?php

namespace App\Models;

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

class Profile extends Model
{
    use HasFactory;

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

In the above code we have created a method user and used belongsTo method to create the relation with User Model.

Laravel assumes here table name is users and foreign key is users table id and owner key is profiles table user_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\Profile;


class UserController extends Controller
{

    public function index(Request $request)
    {

        $profile=Profile::with("user")->first();
        dump($profile);

        dump($profile->user);

    }
}

Step 4 : Create Route

Lastly create the route in web.php

Route::get('/user',[UserController::class, 'index']); 

Related

Php Laravel belongsTOlaravelmysqlrelation

Post navigation

Previous post
Next post

Related Posts

Php How to use conditional where in Laravel 8

How to use conditional where clause in Laravel 8 eloquent ?

February 7, 2022October 4, 2022

In Laravel sometimes while creating a eloquent or db builder query you wanted to apply the where on basis of some conditions and to achieve it you may use if else condition but laravel 8 itself provides solution to handle such type of situations using when method. Laravel eloquent when…

Read More
Php How to Prepend or Append File Content in Laravel

How to Prepend or Append File Content in Laravel ?

May 29, 2022May 29, 2022

In our last article I showed you to create file and this article will cover to Prepend or Append File Content in Laravel application. To perform the file system based operations like create, replace, prepend or append File Content file in laravel, we use File class or Storage class in…

Read More
Php How to use left join in Laravel Eloquent

How to use left join in Laravel eloquent query with example

February 5, 2022February 8, 2024

In this article we will learn to use left join in laravel eloquent and query builder. Laravel itself provide inbuilt method to left join the table like in MySQL or SQL based database we can do join multiple tables using leftJoin function. For example if you have 10 rows and…

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

  • July 2025
  • 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

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version