Laravel's Eloquent ORM is celebrated for its developer-friendly syntax. However, many developers stick to basic CRUD operations without taking advantage of the time-saving helpers built right into the framework.
Here are practical Eloquent tips you can immediately apply to write cleaner, faster, and more readable code.
1. Use `findOr()` for Graceful Fallbacks
Instead of manual if (is_null($user)) checks, use findOr() with a closure callback:
// Clean inline fallback
$user = User::findOr($id, function () {
return User::createGuestUser();
});
2. Eliminate N+1 Queries with Eager Loading
Looping through relationships without eager loading triggers hundreds of unnecessary SQL queries:
// Bad: Runs 1 query for posts + N queries for authors
$posts = Post::all();
// Good: Runs exactly 2 queries total
$posts = Post::with('author')->get();
3. Query Only Needed Columns with `select()`
When fetching thousands of records, pulling heavy columns like description or bio wastes database memory. Fetch only what the view requires:
$users = User::select('id', 'name', 'email')->paginate(20);
4. Clean Conditional Queries with `when()`
Ditch messy if/else statements when building filtered search queries:
$query = Product::query()
->when($request->filled('category'), function ($q) use ($request) {
$q->where('category_id', $request->category);
})
->when($request->filled('min_price'), function ($q) use ($request) {
$q->where('price', '>=', $request->min_price);
})
->get();
5. Atomic Counters with `increment()` and `decrement()`
Avoid race conditions when updating view counts or stock totals:
// Bad: Vulnerable to race conditions
$post->views = $post->views + 1;
$post->save();
// Good: Direct atomic database update
$post->increment('views');
6. Use `firstWhere()` for Quick Lookups
Simplify single-condition searches without chaining where()->first():
$user = User::firstWhere('email', $email);
Summary
Mastering these small Eloquent idioms makes your controllers concise, prevents common performance pitfalls, and makes your codebase a pleasure to read.