📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Laravel Framework Eloquent Relationships

Eloquent Relationships

7 min read Quiz at the end
Define hasMany, belongsTo, belongsToMany relationships and prevent N+1 with eager loading.

Eloquent Relationships

// One-to-Many
class User extends Model {
    public function posts(): HasMany {
        return $this->hasMany(Post::class);
    }
}
class Post extends Model {
    public function user(): BelongsTo {
        return $this->belongsTo(User::class);
    }
}

// Many-to-Many
class Post extends Model {
    public function tags(): BelongsToMany {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }
}

// Has-Many-Through
class Country extends Model {
    public function posts(): HasManyThrough {
        return $this->hasManyThrough(Post::class, User::class);
    }
}

// Eager loading (prevent N+1)
$posts = Post::with(["user", "tags", "comments.user"])->get();

// Attach / detach / sync (many-to-many)
$post->tags()->attach([1, 2, 3]);
$post->tags()->sync([2, 4]);  // replace all
Topic Quiz · 3 questions

Test your understanding before moving on

1. Which relationship method is used for "post belongs to user"?
💡 belongsTo() defines the inverse side of a hasMany relationship.
2. What does eager loading with with() solve?
💡 Eager loading fetches related data in fewer queries, preventing N+1.
3. Which method syncs a many-to-many relationship?
💡 sync() replaces all existing pivot records with the provided IDs.