Writing clean, declarative code with Laravel Eloquent is exceptionally satisfying, but it is easy to accidentally write database queries that degrade performance under load.
In this article, we outline three critical steps to optimize your database layers:
1. Solving the Infamous N+1 Query Bottleneck
When you load a collection of courses and loop over them to display their instructor names, Eloquent will execute one query to fetch the courses, and then separate query statements for each individual course to find its vendor name. This is known as the N+1 problem.
To resolve this instantly, use Eager Loading via the with() helper in your query builder:
// Bad (N+1 query load):
$courses = Course::all();
// Optimized (2 queries total):
$courses = Course::with('vendor')->get();
2. Restricting Selected Columns
By default, calling Course::all() selects all columns (SELECT *). If you have a column holding heavy text descriptions, this consumes substantial memory. Restrict your queries to pull only necessary keys using select():
$courses = Course::select(['id', 'title', 'slug', 'price'])->get();
3. Profiling with Database Indexes
Ensure foreign keys (such as user_id and course_id) are indexed within your migration tables. This allows SQLite or MySQL to traverse rows instantly rather than performing sequential table scans.