Laravel
Beginner
1 min read
Query Builder and Advanced Eloquent
Example
<?php
// Advanced Eloquent queries
use App\Models\Post;
use Illuminate\Support\Facades\DB;
// whereHas: posts that have at least one published comment
$posts = Post::whereHas('comments', function ($query) {
$query->where('approved', true);
})->get();
// withCount: add comments_count column without loading comments
$posts = Post::withCount('comments')->latest()->paginate(10);
// Subquery select: latest comment date per post
$posts = Post::addSelect([
'latest_comment_at' => \App\Models\Comment::select('created_at')
->whereColumn('post_id', 'posts.id')
->latest()
->limit(1),
])->get();
// Chunking for large datasets
Post::chunk(200, function ($posts) {
foreach ($posts as $post) {
// process $post
}
});
// Upsert multiple rows
Post::upsert([
['slug' => 'hello-world', 'title' => 'Hello World', 'user_id' => 1],
['slug' => 'second-post', 'title' => 'Second Post', 'user_id' => 1],
], uniqueBy: ['slug'], update: ['title']);
// Raw query via DB facade
$results = DB::select('SELECT id, title FROM posts WHERE status = ?', ['published']);
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel