Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Blog · Laravel

Laravel Eloquent Relationships Explained with Real Examples

Laravel Eloquent Relationships Explained with Real Examples

Eloquent relationships are where Laravel stops feeling like "just PHP with a query builder" and starts feeling like a real ORM. Understanding these five relationship types covers the vast majority of real-world schemas.

One to Many: A Post Has Many Comments

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

Now $post->comments gives you every comment, and Laravel writes the WHERE post_id = ? for you. The inverse lives on Comment:

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

Many to Many: Posts and Tags

This needs a pivot table (conventionally named alphabetically, e.g. post_tag):

public function tags()
{
    return $this->belongsToMany(Tag::class);
}

Attach and detach tags without writing any SQL: $post->tags()->attach($tagId) or sync([1, 2, 3]) to set the exact list in one call.

Has One Through and Has Many Through

These solve the "grandparent" relationship problem — say, a Country that wants all Posts belonging to Users who belong to that country, without loading Users in between:

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

The N+1 Query Trap

Looping over posts and accessing $post->comments inside the loop fires one query PER post — invisible in development with 10 rows, catastrophic in production with 10,000. Eager load instead:

$posts = Post::with('comments')->get();

This runs exactly two queries total regardless of how many posts there are. Laravel Debugbar or the DB::listen() facade will show you exactly when you've missed one.

Polymorphic Relationships

When both Post and Video need comments, a polymorphic relationship avoids two separate comments tables:

public function commentable()
{
    return $this->morphTo();
}

Master these five patterns and you can model almost any real-world data structure without reaching for raw SQL.

Laravel for Beginners: Setting Up Your First Project

Laravel for Beginners: Setting Up Your First Project

A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.

Building a REST API with Laravel: A Complete Guide

Building a REST API with Laravel: A Complete Guide

API routes, resources, Form Request validation, correct status codes, and Sanctum auth — a real, production-reasonable Laravel API.

Queues and Jobs in Laravel: Processing Tasks in the Background

Queues and Jobs in Laravel: Processing Tasks in the Background

Why anything that talks to the outside world belongs in a queued job, and how to dispatch, delay, and chain them correctly.

Esc