Laravel Eloquent Cheat Sheet (Clean, Practical & Developer-Friendly)

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 rows
  • whereHas() → 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.

MethodMain PurposeSimple Meaning / When You Use ItUsage Type
where()Filter recordsGet only rows matching some conditionSingle table
whereIn()Match multiple valuesGet rows where column value exists in given arraySingle table
whereNotIn()Exclude multiple valuesIgnore rows whose values exist in given arraySingle table
whereNull()Check NULL valuesGet rows where column is empty/NULLSingle table
whereNotNull()Check NOT NULL valuesGet rows where column has valueSingle table
findOrFail()Get one record or 404Fetch one row by ID; fail automatically if not foundSingle table
updateOrCreate()Update or insertUpdate existing row or create new one if missingSingle table
pluck()Get single column valuesExtract only needed column values instead of full rowsSingle table
groupBy()Group similar rowsCombine rows based on same column valueSingle + Aggregate
having()Filter grouped resultsApply condition after groupingSingle + Aggregate
orderBy()Sort recordsArrange rows ascending/descendingSingle table
latest()Sort newest firstOrder by newest created_atSingle table
oldest()Sort oldest firstOrder by oldest created_atSingle table
count()Count rowsGet total number of recordsAggregate
sum()Add column valuesCalculate total of numeric columnAggregate
avg()Average valuesCalculate average of numeric columnAggregate
min()Smallest valueGet minimum value from columnAggregate
max()Largest valueGet maximum value from columnAggregate
when()Conditional queryAdd query conditions only when some condition is trueBoth
paginate()Split into pagesShow data in smaller chunks/pagesBoth
with()Load relations togetherFetch related table data along with main dataRelationship table
withCount()Count related recordsGet number of related rows without loading all dataRelationship table
withAvg()Average related valuesGet average column value from related tableRelationship table
whereHas()Filter by relationGet records only if related table matches conditionRelationship table
load()Load relation laterFetch related data after main model is already loadedRelationship 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() → use pluck()
  • remember() → no longer in core
  • getCached() → 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.