Hornbill LitePress
Clara Osei · PHP ·

N+1 Queries — Finding and Fixing Them

A practical guide to n+1 Queries — Finding and Fixing Them — tips, best practices, and real-world examples.

# N+1 Queries — Finding and Fixing Them

N+1 queries are a silent performance killer.

## The Problem

```php
// N+1 problem
$posts = Post::all();
foreach ($posts as $post) {
echo $post->category->name; // Query per post!
}
```

100 posts = 101 queries!

## The Solution: Eager Loading

```php
// Fixed with eager loading
$posts = Post::with('category')->get();
foreach ($posts as $post) {
echo $post->category->name; // No extra query!
}
```

100 posts = 2 queries!

## Detecting N+1

### Laravel Debugbar

Shows all queries executed — look for patterns.

### Listen to Queries

```php
DB::listen(function ($query) {
Log::debug($query->sql);
});
```

## Best Practices

1. Always eager load relationships you'll access
2. Use `with()` for collections
3. Use `load()` when you already have models

## Conclusion

N+1 queries are easy to fix once detected. Always eager load!
Database Performance Laravel

Written by

C
Clara Osei

Backend engineer, database nerd, and occasional conference speaker.

← Back to Clara Osei's posts