Laravel Eloquent Relationships

Laravel Eloquent Relationships

Eloquent relationships make it easy to work with related database tables using expressive, readable PHP code.

1 - One to Many

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

// Post belongs to User
class Post extends Model
{
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

// Usage
$posts = $user->posts;            // Collection of posts
$author = $post->user;            // Single User model
$user->posts()->create([...]);    // Create a related post

2 - Many to Many

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

// Usage
$post->tags()->attach($tagId);
$post->tags()->sync([$tagId1, $tagId2]);
$post->tags()->detach($tagId);

3 - Has One / Has One Through

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

4 - Eager Loading (Prevents N+1)

// Load posts with their author and tags in 2 queries total
$posts = Post::with(['user', 'tags'])->latest()->get();

// Conditional eager loading
$posts = Post::with(['comments' => fn ($q) => $q->latest()->limit(3)])->get();

// Lazy eager loading on an existing collection
$posts->load('user');

Note: Always use eager loading (with()) when you access relationships inside a loop. Without it, Eloquent fires a separate query for every item — the N+1 problem.

-Tip-