Skip to content
Guest
Laravel · Course Syllabus Show lessons
Database & Eloquent · 8 min read · Intermediate

Eloquent Relationships & Fixing N+1 Queries

Model `hasMany`, `belongsTo`, and `belongsToMany` relations and eliminate N+1 bottlenecks with eager loading.

What you'll learn

  • Define `hasMany`, `belongsTo`, and `belongsToMany` relationships cleanly
  • Eliminate N+1 query storms using `with()` and `withCount()`
  • Select only needed columns in eager loads (`author:id,name`)

Overview

Model hasMany, belongsTo, and belongsToMany relations and eliminate N+1 bottlenecks with eager loading.

Code Example

<?php
// BAD: triggers 1 query for posts + N queries for each author (N+1)
$posts = Post::latest()->take(20)->get();

// GOOD: eager load in exactly 2 SQL queries
$posts = Post::with(['author:id,name', 'tags:id,name'])
    ->withCount('comments')
    ->latest()
    ->paginate(20);

Key Takeaways

  • Define hasMany, belongsTo, and belongsToMany relationships cleanly
  • Eliminate N+1 query storms using with() and withCount()
  • Select only needed columns in eager loads (author:id,name)

Quick Check

Check Your Understanding

Score: 0 / 1

1. How many SQL queries does `Post::with('author')->limit(50)->get()` execute?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind