If you’ve worked with Eloquent for a while, you’ve probably experienced this:
“I know Laravel can do this… but I don’t remember the exact method.”
This guide is a clean, structured, and practical Eloquent cheat sheet designed not just to list methods—but to help you understand when and why to use them.
🧠 Eloquent Mental Model (Read This First)
Before diving into methods, understand this:
with()→ eager load relationships before query (SQL level)load()→ eager load relationships after query (PHP level)where()→ filter rowswhereHas()→ filter based on relationships*OrFail()→ throw exception if not found- Query Builder → builds SQL
- Model → represents actual data
👉 If you remember this, Eloquent becomes much easier.
| Method | Main Purpose | Simple Meaning / When You Use It | Usage Type |
|---|---|---|---|
where() | Filter records | Get only rows matching some condition | Single table |
whereIn() | Match multiple values | Get rows where column value exists in given array | Single table |
whereNotIn() | Exclude multiple values | Ignore rows whose values exist in given array | Single table |
whereNull() | Check NULL values | Get rows where column is empty/NULL | Single table |
whereNotNull() | Check NOT NULL values | Get rows where column has value | Single table |
findOrFail() | Get one record or 404 | Fetch one row by ID; fail automatically if not found | Single table |
updateOrCreate() | Update or insert | Update existing row or create new one if missing | Single table |
pluck() | Get single column values | Extract only needed column values instead of full rows | Single table |
groupBy() | Group similar rows | Combine rows based on same column value | Single + Aggregate |
having() | Filter grouped results | Apply condition after grouping | Single + Aggregate |
orderBy() | Sort records | Arrange rows ascending/descending | Single table |
latest() | Sort newest first | Order by newest created_at | Single table |
oldest() | Sort oldest first | Order by oldest created_at | Single table |
count() | Count rows | Get total number of records | Aggregate |
sum() | Add column values | Calculate total of numeric column | Aggregate |
avg() | Average values | Calculate average of numeric column | Aggregate |
min() | Smallest value | Get minimum value from column | Aggregate |
max() | Largest value | Get maximum value from column | Aggregate |
when() | Conditional query | Add query conditions only when some condition is true | Both |
paginate() | Split into pages | Show data in smaller chunks/pages | Both |
with() | Load relations together | Fetch related table data along with main data | Relationship table |
withCount() | Count related records | Get number of related rows without loading all data | Relationship table |
withAvg() | Average related values | Get average column value from related table | Relationship table |
whereHas() | Filter by relation | Get records only if related table matches condition | Relationship table |
load() | Load relation later | Fetch related data after main model is already loaded | Relationship table |
🔹 1. Query Builder (Before Fetching Data)
Select
select('col1', 'col2')
select(['col1', 'col2'])
addSelect('col3')
distinct()select(DB::raw('COUNT(*) as total'))Use raw SQL for complex expressions.
Where Conditions
where('column', 'value')
where('column', 'LIKE', '%value%')
orWhere('column', '!=', 'value')Grouped conditions
where(function ($query) {
$query->where('a', 1)
->orWhere('b', 1);
})Raw conditions
whereRaw('age > ? AND votes = 100', [25])Advanced Filters
whereIn('id', [1,2,3])
whereNotIn('id', [...])
whereNull('column')
whereNotNull('column')Date filtering
whereDate('created_at', '2024-01-01')
whereMonth('created_at', 1)
whereYear('created_at', 2025)Conditional Queries (Very Useful)
when($search, function ($query) use ($search) {
$query->where('title', 'like', "%$search%");
})👉 Keeps your code clean and avoids if clutter.
🔹 2. Joins
join('table', 'a', '=', 'b')
leftJoin('table', 'a', '=', 'b')Advanced join
join('table', function ($join) {
$join->on('a', '=', 'b')
->where('status', 1);
})🔹 3. Relationships & Eager Loading
Basic eager loading
with('reviews')
with(['reviews', 'author'])Conditional eager loading
with(['reviews' => function ($q) {
$q->where('rating', '>', 4);
}])Aggregates
withCount('reviews')
withAvg('reviews', 'rating')After fetching (Lazy eager loading)
$book->load('reviews');
$book->loadCount('reviews');
$book->loadAvg('reviews', 'rating');Relationship filtering
whereHas('reviews', function ($q) {
$q->where('rating', '>', 4);
})🔹 4. Grouping & Aggregates
groupBy('category_id')
having('count', '>', 1)
havingRaw('COUNT(*) > 1')🔹 5. Ordering & Limiting
orderBy('id', 'DESC')
latest() // by created_at
oldest()limit(10)
offset(10)
forPage($page, $perPage)🔹 6. Retrieving Data
get()
first()
firstOrFail()
find($id)
findOrFail($id)
all()🔹 7. Pagination
paginate(10)
simplePaginate(10)🔹 8. Insert / Create
insert([...])
insertGetId([...])Model-based
Model::create([...])
firstOrCreate([...])
updateOrCreate([...])🔹 9. Update
update([...])
increment('views')
decrement('stock')
touch()🔹 10. Delete
delete()
destroy([1,2,3])
forceDelete()Relationships
$book->tags()->detach();🔹 11. Collections & Helpers
pluck('name')
value('name')
implode('name', ',')🔹 12. Chunking (Large Data)
chunk(1000, function ($rows) {
// process
})👉 Prevents memory issues.
🔹 13. Aggregates
count()
sum('price')
avg('price')
min('price')
max('price')🔹 14. Debugging
toSql()
DB::enableQueryLog();
DB::getQueryLog();🔹 15. Model Instance Methods
toArray()
toJson()isDirty()
getDirty()fresh()🔹 16. Existence Checks
exists()
doesntExist()⭐ Most Used Methods (Daily Use)
If you only focus on these, you’ll be productive fast:
with()where()findOrFail()withCount()when()whereHas()paginate()updateOrCreate()load()pluck()
⚡ Performance Tips
- ✅ Use
with()to avoid N+1 queries - ✅ Use
select()instead of* - ✅ Use
chunk()for large datasets - ❌ Avoid queries inside loops
- ❌ Avoid overusing
DB::raw()
❌ Deprecated / Avoid
lists()→ usepluck()remember()→ no longer in coregetCached()→ not standard Eloquent
🧪 Real-World Example
Book::withCount('reviews')
->whereHas('reviews', fn($q) => $q->where('rating', '>', 4))
->when($search, fn($q) => $q->where('title', 'like', "%$search%"))
->latest()
->paginate(10);🚀 Final Thoughts
You don’t need to memorize everything.
Focus on:
- Query building (
where,with) - Data retrieval (
get,findOrFail) - Relationships (
withCount,whereHas)
Everything else becomes intuitive with practice.
👉 Keep this as your daily reference, and over time, Eloquent will feel second nature.
