0
0
LaravelHow-ToBeginner · 3 min read

How to Use belongsTo in Eloquent: Laravel Relationship Guide

In Laravel Eloquent, use belongsTo to define an inverse one-to-many relationship from a child model to its parent. Add a belongsTo method in the child model that returns $this->belongsTo(ParentModel::class) to link them.
📐

Syntax

The belongsTo method is used inside a child model to define its parent relationship. It typically looks like this:

  • return $this->belongsTo(ParentModel::class); - links the child to the parent model.
  • The foreign key defaults to parent_model_id but can be customized.
  • The owner key defaults to id on the parent model.
php
public function parent()
{
    return $this->belongsTo(ParentModel::class, 'foreign_key', 'owner_key');
}
💻

Example

This example shows a Comment model that belongs to a Post model. Each comment is linked to one post.

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Post model code here
}

class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

// Usage example
$comment = Comment::find(1);
echo $comment->post->title;
Output
The title of the post that the comment with ID 1 belongs to will be printed.
⚠️

Common Pitfalls

Common mistakes when using belongsTo include:

  • Not defining the relationship method in the child model.
  • Using the wrong foreign key name if it differs from the default.
  • Trying to call belongsTo on the parent model instead of the child.
  • Forgetting to access the relationship as a property ($comment->post) instead of a method ($comment->post()).
php
<?php
// Wrong: calling belongsTo on parent model
class Post extends Model
{
    public function comment()
    {
        return $this->belongsTo(Comment::class); // Incorrect
    }
}

// Right: belongsTo on child model
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class); // Correct
    }
}
📊

Quick Reference

ConceptDescriptionDefault Value
belongsTo methodDefines inverse one-to-many from child to parentN/A
Foreign keyColumn in child model referencing parentparent_model_id
Owner keyPrimary key in parent modelid
Accessing relationUse as property to get parent model$child->parent

Key Takeaways

Use belongsTo in the child model to link it to its parent model.
The foreign key defaults to parent_model_id but can be customized in belongsTo parameters.
Access the related parent model as a property, not a method.
belongsTo defines the inverse side of a one-to-many relationship.
Always define the relationship method inside the child model.