Skip to main content

Pagination and Database Performance

13/28
Chapter 3 Eloquent ORM and Database Mastery

Pagination and Database Performance

16 min read Lesson 13 / 28

Pagination and Query Performance

Efficient data retrieval and proper pagination are essential for scalable applications. Never load unlimited records.

Built-In Pagination

// Standard pagination with page links
$posts = Post::published()->latest()->paginate(15);

// Simple prev/next pagination (faster for large tables)
$posts = Post::published()->latest()->simplePaginate(15);

// Cursor pagination (most efficient for infinite scroll)
$posts = Post::published()->latest()->cursorPaginate(15);

In Blade:

@foreach($posts as $post)
    <article>{{ $post->title }}</article>
@endforeach

{{ $posts->links() }}  {{-- Renders pagination links --}}

Preventing N+1 Queries

The most common performance mistake in Laravel is N+1 queries:

// BAD: N+1 problem — 1 query for posts + N queries for authors
$posts = Post::all();
@foreach($posts as $post)
    {{ $post->author->name }}  // Each access = 1 query
@endforeach

// GOOD: Eager loading — only 2 queries total
$posts = Post::with('author')->get();

Automatic Eager Loading (Laravel 12.8+)

// In AppServiceProvider
public function boot(): void
{
    // Prevent lazy loading in development
    Model::preventLazyLoading(! app()->isProduction());
}

This throws an exception when you accidentally trigger a lazy load, helping you catch N+1 problems early.

Indexing Strategy

// In your migration, index columns you filter/sort by
$table->index('published_at');
$table->index(['is_published', 'published_at']); // Composite index
$table->index('category_id');

Query Debugging

// See the raw SQL
$query = Post::with('author')->published()->toRawSql();
logger($query);

// Count queries in a request (in development)
DB::enableQueryLog();
// ... your code ...
dd(DB::getQueryLog());

Efficient queries combined with proper pagination keep your application fast regardless of data volume.