Eloquent is the reason many developers love Laravel. A few lines of readable PHP replace pages of raw SQL, and relationships feel like plain object properties. But that comfort hides a trap: Eloquent makes it very easy to write queries that work perfectly in development and fall apart in production, when a table grows from a hundred rows to a hundred thousand.
The good news is that most slow Eloquent code comes from a small set of repeatable mistakes — and each one has a simple fix. Here are 10 Laravel Eloquent tips and tricks I actually use, with the before-and-after code for each.
1. Eager load relationships and kill the N+1 problem
This is the single most common Eloquent performance bug. When you loop over posts and read $post->user->name inside the loop, Eloquent runs one query for the posts, then one extra query per post to fetch its author. With 100 posts, that is 101 queries.
// Slow: 1 + 100 queries
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name;
}
// Fast: just 2 queries
$posts = Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name;
}
The with() call tells Eloquent to fetch all the authors in one second query. Whenever a Blade view or an API resource touches a relationship inside a loop, eager loading belongs in the query, not in the loop. If you only need a count, use withCount() instead — tip 6 covers that.
2. Select only the columns you actually need
By default Eloquent runs SELECT *. On a wide table — one with long text columns or JSON blobs — that pulls far more data than any page needs, and the memory cost grows with every row.
// Fetches every column, including big text fields
$users = User::all();
// Fetches only what the page uses
$users = User::select('id', 'name', 'email')->get();
One rule: always include the primary key and any foreign keys the relationships need. If you select name but forget id, Eloquent cannot match related models to their parents, and your eager loads will silently come back empty.
3. Use exists() instead of count() to check for a record
Checking whether a record exists is one of the most frequent queries in any application — "is this email taken?", "has this user already voted?" — and count() is the slow way to answer it, because the database counts every matching row before returning.
// Counts ALL matching rows, then checks the number
if (User::where('email', $email)->count() > 0) { }
// Stops at the first match — SELECT 1 ... LIMIT 1
if (User::where('email', $email)->exists()) { }
exists() generates a query that stops as soon as it finds one match. On a table with thousands of matches, the difference is the difference between scanning them all and stopping at the first one.
4. Never load a whole table into memory — chunk it
User::all() on a table with a million rows tries to build a million model objects at once. That is how a routine export or nightly job runs out of memory at 3 a.m. Chunk the work instead:
User::chunk(500, function ($users) {
foreach ($users as $user) {
// process 500 users at a time
}
});
If the data changes while you process it — rows being added or deleted mid-run — use chunkById() instead, which pages by primary key and will not skip or repeat rows. For read-only jobs where you want the lowest possible memory, cursor() streams one model at a time using a PHP generator:
foreach (User::cursor() as $user) {
// only one model in memory at a time
}
And in Laravel 13, lazyById() gives you the same streaming behaviour with safe ordering by ID — the best choice for very large exports.
5. Put repeated conditions in query scopes
If the same where('status', 'active') appears in five controllers, it will eventually appear in a sixth place with a typo. A local scope on the model keeps the rule in exactly one place:
// In the User model
public function scopeActive($query)
{
return $query->where('status', 'active');
}
public function scopeRecent($query)
{
return $query->where('created_at', '>=', now()->subDays(30));
}
// Anywhere in the app
$users = User::active()->recent()->get();
Scopes chain like any other query builder method, and they make the calling code read like plain English. When a business rule changes — "active" starts meaning something slightly different — you change one method, not five controllers.
6. Count relationships with withCount(), not by loading them
Showing "12 comments" next to each post does not require loading 12 comment models per post. withCount() adds a single {relation}_count attribute with one extra query for the whole list:
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->title . ' (' . $post->comments_count . ' comments)';
}
You can even constrain the count — withCount(['comments' => fn ($q) => $q->where('approved', true)]) — which is far cheaper than loading every comment and counting in PHP.
7. Create or update in one call with firstOrCreate and updateOrCreate
"Find this record, or create it if it is missing" is another pattern that shows up everywhere — settings rows, tags, sync jobs. Writing it by hand means two queries and a race condition; Eloquent has it built in:
// Find by email, or create with these attributes
$user = User::firstOrCreate(
['email' => $email],
['name' => $name]
);
// Find by email, or create — and update the name if it exists
$user = User::updateOrCreate(
['email' => $email],
['name' => $name]
);
The first array is the lookup; the second is what gets written. One call, one clear intent, and no window where two requests create the same record twice.
8. Let the database do the maths
Fetching a thousand order rows into PHP just to add up their totals is slow in two ways: the database sends all the data, and PHP loops over all of it. Aggregate functions run where the data already lives:
// Slow: loads every order, sums in PHP
$total = Order::where('status', 'completed')->get()->sum('total');
// Fast: the database returns one number
$total = Order::where('status', 'completed')->sum('total');
The same applies to count(), avg(), min() and max(). As a rule of thumb, if the answer is a single number, the database should compute it — your application should never receive rows it is only going to collapse into one value.
9. Use firstOrFail() and findOrFail() for missing records
Manually checking for null after every lookup is noisy code, and forgetting the check is how "Trying to get property of non-object" errors reach production. Eloquent's OrFail methods throw a ModelNotFoundException, which Laravel automatically turns into a clean 404 response:
// Manual check — easy to forget
$post = Post::find($id);
if (! $post) {
abort(404);
}
// Same result, one line, impossible to forget
$post = Post::findOrFail($id);
In controllers, this also pairs well with route model binding — type-hint the model in the method signature and Laravel resolves it (or 404s) before your code even runs.
10. Cache the queries that do not change often
Some queries are expensive and their results barely change: the list of categories in a sidebar, the featured posts on a homepage, the settings table. Running them on every request is pure waste. Cache::remember() runs the query once and serves the stored result until it expires:
$categories = Cache::remember('sidebar_categories', 3600, function () {
return Category::withCount('posts')->orderBy('name')->get();
});
The one discipline this needs is invalidation: whenever a category is created, updated or deleted, forget the key (Cache::forget('sidebar_categories')). A stale cache is worse than a slow query, because it serves wrong data confidently. A good habit is to put the forget() call in the model's saved and deleted events, so no controller can forget it.
Frequently asked questions
What is the N+1 query problem in Laravel?
It happens when Eloquent runs one query for a list of models and then one more query per model to load a relationship — so 100 posts produce 101 queries. Fix it with eager loading: Post::with('user')->get().
Should I use Eloquent or raw SQL for complex queries?
Use Eloquent for almost everything; it is safer (parameter binding prevents SQL injection) and far more readable. Reach for the query builder or DB::raw() only for queries Eloquent genuinely cannot express well, like complex window functions — and keep those in one place, not scattered through controllers.
How do I find my slowest Eloquent queries?
Install Laravel Telescope in development, or add a temporary DB::listen() callback that logs every query with its time. Fix the slowest queries first — in practice, one N+1 loop or one missing index usually accounts for most of the total time.
Wrapping up
Faster Eloquent is rarely about clever tricks — it is about not asking the database for work you do not need. Eager load relationships instead of querying in loops, select only the columns you use, check existence with exists(), chunk large datasets, push counting and summing into the database, and cache the results that rarely change. Apply these 10 Laravel Eloquent tips and tricks to the slowest page in your app first: measure it before and after with Telescope, and you will usually find one or two of these tips account for almost all of the improvement.