Blog Details
Mastering Laravel Eloquent: Advanced Query Techniques

Laravel Eloquent is one of the most powerful and elegant ORM (Object-Relational Mapping) tools available for PHP developers. While basic CRUD operations are straightforward with Eloquent, mastering its advanced query techniques can significantly boost your application's performance and maintainability.
In this blog post, we will explore advanced Eloquent query methods like eager loading, query scopes, joins, subqueries, and more. These techniques will help you write efficient, readable, and scalable code that interacts seamlessly with your database.
Why Master Advanced Eloquent Queries?
- Performance: Avoid the N+1 query problem using eager loading.
- Readability: Keep queries clean and reusable with scopes.
- Flexibility: Perform complex joins and subqueries easily.
- Maintainability: Write modular and efficient data retrieval logic.
1. Eager Loading to Avoid N+1 Problem
When you retrieve a model and access its related models in a loop, Laravel runs additional queries for each related model, causing the infamous N+1 problem.
Solution: Use eager loading with with()
.
// Without eager loading (N+1 problem)
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
// With eager loading (optimized)
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name;
}
Eager loading retrieves all related models in a single query, reducing database load drastically.
2. Query Scopes for Reusable Query Logic
Query scopes allow you to encapsulate common query logic within your models for reusability and cleaner controllers.
Example: Defining a scope to get published posts
// In Post model
public function scopePublished($query)
{
return $query->where('status', 'published');
}
Using the scope
$publishedPosts = Post::published()->get();
Scopes can also accept parameters:
public function scopePopular($query, $minViews = 100)
{
return $query->where('views', '>=', $minViews);
}
$popularPosts = Post::popular(500)->get();
3. Advanced Joins with Eloquent
While Eloquent encourages relationships, sometimes you need custom join queries to fetch data.
$users = User::join('posts', 'users.id', '=', 'posts.user_id')
->select('users.*', 'posts.title')
->where('posts.published', true)
->get();
Laravel also supports left joins, cross joins, and raw joins for complex scenarios.
4. Subqueries for Complex Filters
Subqueries allow you to embed queries inside other queries for complex data retrieval.
Example: Get users who have written more than 5 posts.
use Illuminate\Database\Eloquent\Builder;
$users = User::whereHas('posts', function (Builder $query) {
$query->select(DB::raw('count(*)'))
->groupBy('user_id')
->havingRaw('count(*) > ?', [5]);
})->get();
You can also select subqueries directly:
$users = User::select('users.*')
->selectSub(function ($query) {
$query->from('posts')
->selectRaw('count(*)')
->whereColumn('posts.user_id', 'users.id');
}, 'posts_count')
->get();
5. Using Aggregates and Grouping
Eloquent provides aggregate functions such as count()
, max()
, min()
, avg()
, and sum()
.
// Count of published posts
$publishedCount = Post::where('status', 'published')->count();
// Average post views
$averageViews = Post::avg('views');
// Grouping example
$postsByAuthor = Post::select('author_id', DB::raw('count(*) as total'))
->groupBy('author_id')
->get();
6. Chunking for Memory Efficiency
When processing large datasets, use chunking to avoid memory overload.
Post::chunk(100, function ($posts) {
foreach ($posts as $post) {
// Process each post
}
});
7. Conditional Clauses with when()
You can conditionally add query constraints with when()
for cleaner code.
$query = Post::query();
$query->when($request->filled('author'), function ($q) use ($request) {
return $q->where('author_id', $request->author);
});
$posts = $query->get();
Conclusion
Mastering these advanced Eloquent query techniques can transform how you interact with your database in Laravel. Not only will you improve your app’s performance, but you’ll also keep your codebase clean, scalable, and easy to maintain.
Start implementing these strategies today to take your Laravel projects to the next level!
Further Reading
If you found this post helpful, please share it and subscribe for more Laravel tips and tutorials!