Laravel Eloquent Relationships: Complete Guide with Examples

Laravel Eloquent Relationships: Complete Guide with Examples

Laravel Eloquent Relationships: Complete Guide with Examples

Laravel Eloquent Relationships are one of the most important concepts when working with databases in Laravel. They allow you to easily connect models such as Users, Posts, Comments, Products and Categories without writing complex SQL queries.

In this guide, we will learn Laravel Eloquent relationships from beginner to advanced level with practical examples.

We will cover One-to-One, One-to-Many, Many-to-Many, belongsTo, hasMany, belongsToMany, eager loading and common relationship mistakes.

What is Laravel Eloquent?

Eloquent is Laravel's Object-Relational Mapper (ORM). It allows developers to work with database tables using PHP models instead of writing SQL queries for every operation.

For example, instead of manually writing a SQL query to retrieve users, you can use:

$users = User::all();

Eloquent also makes it easy to define relationships between different database tables.

What are Eloquent Relationships?

Suppose you have a website with users and blog posts.

  • One user can create many posts.
  • Each post belongs to one user.
  • A post can have many comments.
  • A post can belong to multiple categories.

These connections between models are called Eloquent Relationships.

Types of Laravel Eloquent Relationships

Relationship Example Laravel Method
One-to-One User → Profile hasOne()
One-to-Many User → Posts hasMany()
Many-to-One Post → User belongsTo()
Many-to-Many Posts ↔ Categories belongsToMany()

1. One-to-One Relationship

A One-to-One relationship means one record is associated with exactly one record from another table.

For example:

One User has one Profile.

User Model

public function profile()
{
    return $this->hasOne(Profile::class);
}

Profile Model

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

Get User Profile

$user = User::find(1);

$profile = $user->profile;

Laravel automatically understands the relationship using the conventional foreign key.

2. One-to-Many Relationship

One-to-Many is one of the most commonly used relationships in Laravel applications.

For example:

One User can have many Posts.

User Model

public function posts()
{
    return $this->hasMany(Post::class);
}

Post Model

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

Get All Posts of a User

$user = User::find(1);

$posts = $user->posts;

You can loop through the posts like this:

foreach ($user->posts as $post) {
    echo $post->title;
}

3. Many-to-One Relationship

A Many-to-One relationship is basically the reverse side of a One-to-Many relationship.

For example, many posts can belong to one user.

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

Now you can access the author of a post:

$post = Post::find(10);

echo $post->user->name;

4. Many-to-Many Relationship

A Many-to-Many relationship means multiple records from one table can be connected to multiple records from another table.

A common example is:

Posts can have multiple Categories and Categories can contain multiple Posts.

Usually, this relationship requires a pivot table.

Example database structure:

  • posts
  • categories
  • category_post

Post Model

public function categories()
{
    return $this->belongsToMany(Category::class);
}

Category Model

public function posts()
{
    return $this->belongsToMany(Post::class);
}

Get Categories of a Post

$post = Post::find(1);

$categories = $post->categories;

Attach a Category

$post->categories()->attach($categoryId);

Detach a Category

$post->categories()->detach($categoryId);

Sync Categories

$post->categories()->sync([1, 2, 3]);
Tip: The sync() method is useful when you want to update a Many-to-Many relationship and keep only the selected IDs.

5. Eager Loading in Laravel

Eager loading is very important when working with relationships because it can help avoid unnecessary database queries.

Suppose you want to retrieve users and their posts.

Instead of loading relationships repeatedly, you can use the with() method.

$users = User::with('posts')->get();

Now the posts relationship is loaded along with the users.

Multiple Relationships

$users = User::with([
    'posts',
    'profile'
])->get();

6. Nested Eager Loading

Laravel also allows you to eager load nested relationships.

For example, load users, their posts and comments:

$users = User::with([
    'posts.comments'
])->get();

This is useful for applications with multiple connected models.

7. Lazy Loading

Lazy loading means the relationship data is loaded only when you actually access it.

$user = User::find(1);

$posts = $user->posts;

The posts relationship is loaded when $user->posts is accessed.

Important: Lazy loading is convenient, but loading relationships repeatedly inside large loops can result in many database queries.

8. Counting Related Records

Sometimes you don't need the complete relationship data. You only need the count.

Laravel provides withCount() for this purpose.

$users = User::withCount('posts')->get();

Now you can access:

echo $user->posts_count;

9. Relationship Conditions

You can also add conditions when retrieving related models.

$users = User::with([
    'posts' => function ($query) {
        $query->where('status', 'published');
    }
])->get();

This example loads only published posts for each user.

10. Custom Foreign Keys

Laravel follows naming conventions automatically. However, sometimes your database uses a custom foreign key.

In that case, you can specify the foreign key manually.

public function posts()
{
    return $this->hasMany(
        Post::class,
        'author_id'
    );
}

Common Eloquent Relationship Mistakes

1. Incorrect Foreign Key

If the foreign key doesn't follow Laravel's convention, explicitly define it in the relationship.

2. Forgetting Eager Loading

Loading relationships inside large loops can cause unnecessary database queries. Use with() when appropriate.

3. Incorrect Pivot Table Name

Many-to-Many relationships depend on the pivot table. Make sure the table and foreign keys are correctly configured.

4. Loading More Data Than Required

Don't load large relationships if your page only needs a small amount of data. Select the required fields and relationships carefully.

Laravel Eloquent Relationships Example

Imagine an e-commerce application with the following relationships:

  • One customer has many orders.
  • One order belongs to one customer.
  • One order has many products.
  • One product belongs to many orders.

Your models could contain relationships such as:

// Customer.php

public function orders()
{
    return $this->hasMany(Order::class);
}


// Order.php

public function customer()
{
    return $this->belongsTo(Customer::class);
}

public function products()
{
    return $this->belongsToMany(Product::class);
}


// Product.php

public function orders()
{
    return $this->belongsToMany(Order::class);
}

This structure makes it much easier to retrieve connected data in your application.

Eloquent Relationship Cheat Sheet

Method Use Case
hasOne() One model has one related model
hasMany() One model has many related models
belongsTo() Current model belongs to another model
belongsToMany() Many-to-Many relationship
with() Eager load relationships
withCount() Count related records
attach() Add records to a Many-to-Many relationship
detach() Remove records from a Many-to-Many relationship
sync() Synchronize Many-to-Many relationships

Best Practices for Eloquent Relationships

  1. Use meaningful relationship method names.
  2. Follow Laravel's database naming conventions whenever possible.
  3. Use eager loading when retrieving relationships in bulk.
  4. Avoid unnecessary relationship queries.
  5. Use withCount() when you only need relationship counts.
  6. Keep your model relationships organized and easy to understand.
  7. Use appropriate indexes on foreign key columns.

Frequently Asked Questions

What is Eloquent in Laravel?

Eloquent is Laravel's ORM that allows developers to interact with database tables using PHP models.

What is hasMany() in Laravel?

The hasMany() relationship is used when one model can have multiple related records, such as one user having many posts.

What is belongsTo() in Laravel?

The belongsTo() relationship indicates that the current model belongs to another model.

What is belongsToMany()?

belongsToMany() is used for Many-to-Many relationships, usually with a pivot table.

Why should I use eager loading?

Eager loading allows related data to be loaded efficiently and can help reduce unnecessary database queries when working with multiple records.

Conclusion

Laravel Eloquent Relationships make it much easier to work with related database records. Instead of writing complicated SQL queries manually, you can define relationships directly inside your Laravel models.

The most important relationships to understand are hasOne(), hasMany(), belongsTo() and belongsToMany(). Once you understand these relationships, building database-driven Laravel applications becomes much easier.

Start with simple One-to-One and One-to-Many relationships and then move toward Many-to-Many relationships and eager loading.

Keep learning Laravel and building real-world projects!

© DeveloperSahayak | Laravel & Web Development Tutorials

0 Comments