Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 67 ยท Eloquent ORM

Eloquent Relationships

Model one-to-one, one-to-many, many-to-many, has-many-through and polymorphic relationships in Eloquent, and see how a relationship resolver works underneath.

Real data is connected. A user writes posts, a post has comments, a post has many tags and a tag belongs to many posts. In a database these links are foreign keys and pivot tables. In Eloquent they become relationships: methods on your models that describe the link once, so you can write $post->author->name or $user->posts instead of hand-written joins.

This lesson walks through the relationship types, the naming conventions that make them work with almost no configuration, how to query through relations, and how the magic underneath actually works. It builds on Eloquent models and CRUD and querying with Eloquent. Real Laravel code appears in read-only blocks; the runnable examples are PHP stand-ins on SQLite that reproduce the mechanism.

One-to-many: hasMany and belongsTo

The most common relationship. One User has many Post rows, and each post belongs to one user. The foreign key lives on the many side (posts.user_id).

PHP
class User extends Model
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

$user->posts;                 // Collection of Post models (a property!)
$post->author->name;          // the User, loaded on first access
$user->posts()->where('published', true)->get();   // a method call: a query

By convention Eloquent guesses the foreign key from the parent model name: User becomes user_id. If your column is called differently, pass it as the second argument. Notice the two ways to read a relation. $user->posts (property) runs the query once, caches the result on the model and returns a collection. $user->posts() (method) returns the relation object, which is a query builder you can keep constraining, counting or adding to.

Because the relation is a builder, you can create related rows through it, and Eloquent fills in the foreign key for you:

PHP
$post = $user->posts()->create(['title' => 'Hello']);   // user_id set automatically
$comment->post()->associate($post);                      // sets post_id, then save()

One-to-one: hasOne

hasOne is hasMany that returns a single model. A User has one Profile; the foreign key (profiles.user_id) lives on the profile. There is also latestOfMany() and oldestOfMany() to treat the newest row of a has-many as a one-to-one ("the user's latest login").

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

When a belongsTo may point at nothing, such as a post with no author, add ->withDefault() so $post->author->name returns an empty model instead of crashing on null.

Many-to-many: belongsToMany and pivot tables

A post can have many tags and a tag many posts. Neither table can hold the foreign key, so a third pivot table does. By convention it is named after both models in alphabetical order, singular: post_tag, with columns post_id and tag_id.

PHP
class Post extends Model
{
    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class)
            ->withPivot('weight')
            ->withTimestamps();
    }
}

$post->tags()->attach($tagId);                    // add one link
$post->tags()->detach($tagId);                    // remove one
$post->tags()->sync([1, 2, 5]);                   // make the links exactly these
$post->tags()->syncWithoutDetaching([7]);         // add, keep the rest
$post->tags()->toggle([3]);                       // flip each id

foreach ($post->tags as $tag) {
    echo $tag->pivot->weight;                     // extra pivot column
}

sync() is the workhorse for forms with checkboxes: you hand it the complete list of selected ids and it works out what to attach and what to detach. The pivot data is available on each related model as ->pivot. When a pivot row deserves its own behaviour, give it a model and use ->using(PostTag::class).

Has-many-through

Sometimes the link goes through an intermediate table. A Country has many Post rows through User (country, then user, then post). Instead of looping over users, ask for the far side directly:

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

Laravel runs one query with a join. hasOneThrough is the single-row version.

Polymorphic relationships

A polymorphic relationship lets one model belong to more than one type of parent. Comments can belong to posts and to videos. Instead of one foreign key, the comments table holds two columns, commentable_id and commentable_type.

PHP
class Comment extends Model
{
    public function commentable(): MorphTo
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// in AppServiceProvider::boot()
Relation::enforceMorphMap([
    'post'  => Post::class,
    'video' => Video::class,
]);

By default the type column stores the full class name (App\Models\Post), which ties your data to your namespaces. A morph map replaces it with a stable alias such as post. Call Relation::enforceMorphMap() early so a refactor cannot silently break old rows. There are also morphOne, morphToMany and morphedByMany for polymorphic many-to-many (tags shared between posts and videos).

The resolver behind the magic

How can $post->author work when author is a method and not a property? PHP calls __get('author') for the inaccessible property. Eloquent's __get checks the attributes first, then checks whether a relationship method of that name exists. If it does, it calls the method to get the relation object, runs its query, stores the result and returns it. The next access finds the stored result and runs no query.

PHP A relationship resolver with __get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Count the queries: one for Ada's posts, then for each of her two posts one query for the author and one for the tags. That is 1 + 2 + 2 = 5, and it grows with every post. This is the shape of the N+1 problem, which the next lesson fixes.

Querying through relations

Relations are also a way to filter. has() and whereHas() keep only the parents with matching children, using an EXISTS subquery:

PHP
Post::has('comments')->get();                               // at least one comment
Post::has('comments', '>=', 5)->get();                      // five or more
Post::whereHas('comments', fn ($q) => $q->where('approved', true))->get();
Post::doesntHave('tags')->get();                            // posts without any tag
Post::whereBelongsTo($user)->get();                         // posts where user_id = $user->id

whereHas never loads the children; it only decides which parents qualify. If you also need the children, add with(), covered in the next lesson, and for counts use withCount from the previous lesson.

PHP Pivot sync, and whereHas as EXISTS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second sync shows the idea: it attaches only the new id and detaches only the removed one, and the third call, with nothing changed, touches nothing.

Choosing and naming relationships

erDiagram
    USER ||--o{ POST : "hasMany / belongsTo"
    POST }o--o{ TAG : "belongsToMany (post_tag)"
    POST ||--o{ COMMENT : "morphMany"
    VIDEO ||--o{ COMMENT : "morphMany"
    COUNTRY ||--o{ USER : "hasMany"
    COUNTRY ||--o{ POST : "hasManyThrough"

Foreign keys sit on the "many" side; a pivot table holds many-to-many links; comments point at either a post or a video.

A few habits keep relationships healthy. Name a relation after what it returns: plural for collections (posts), singular for one model (author). Always add the foreign key to the migration with a constraint and an index (see migrations). Remember that reading a relationship property inside a loop issues a query per row, so plan your loading before you build the page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the foreign key live in a one-to-many relationship between users and posts?

    The foreign key is always on the "many" side, so each post row stores the id of the user it belongs to.
  2. 2. What is the difference between $user->posts and $user->posts()?

    The property triggers dynamic loading and caches the result on the model. The method gives you the builder, so you can add where clauses, count, or create related rows.
  3. 3. Which call makes a post's tags exactly equal to the ids [2, 3, 4], removing any others?

    sync() computes the difference and attaches the new ids and detaches the missing ones. attach only adds, toggle flips each id, and syncWithoutDetaching never removes.
  4. 4. Why would you register a morph map for polymorphic relations?

    Without a map the type column stores class names such as App\Models\Post, so renaming or moving a class would break existing rows.

Summary

  • Relationships are methods that return relation objects; read them as a property for loaded results or as a method to keep building a query.
  • hasMany/belongsTo use a foreign key on the many side, hasOne returns one row, and belongsToMany uses a pivot table named alphabetically (post_tag).
  • attach, detach, sync and toggle manage pivot rows; withPivot exposes extra pivot columns.
  • hasManyThrough reaches distant rows via an intermediate model; polymorphic relations use an id plus a type column, ideally with a morph map.
  • has, whereHas and doesntHave filter parents by their children with EXISTS subqueries.
  • Lazy loading in a loop causes extra queries, which is the subject of the next lesson.

Next: Eager Loading and the N+1 Problem