Build the derived relation as a subquery and join it, or use an existence predicate when only membership matters: ```php $latest = Comment::query() ->select('post_id', DB::raw('MAX(created_at) AS latest_comment_at')) ->groupBy('post_id'); $posts = Post::query() ->joinSub($latest, 'latest_comments', function ($join) { $join->on('posts.id', '=', 'latest_comments.post_id'); }) ->select('posts.*', 'latest_comments.latest_comment_at') ->get(); ``` For filtering without selecting child rows: ```php...
Scanned 9/5/2026
Install to Claude Code
npx -y skills add HoangNguyen0403/agent-skills-standard --skill laravel-database-expert --agent claude-codeInstalls into .claude/skills of the current project.
Are you the author of Laravel Database Expert?
Add the live security badge to your README — it updates automatically with every re-scan.
[](https://www.skillsdirectory.com/skills/hoangnguyen0403-laravel-database-expert-7b13f172)More formats (shields.io, HTML) on the badges page.
Build the derived relation as a subquery and join it, or use an existence predicate when only membership matters:
```php
$latest = Comment::query()
->select('post_id', DB::raw('MAX(created_at) AS latest_comment_at'))
->groupBy('post_id');
$posts = Post::query()
->joinSub($latest, 'latest_comments', function ($join) {
$join->on('posts.id', '=', 'latest_comments.post_id');
})
->select('posts.*', 'latest_comments.latest_comment_at')
->get();
```
For filtering without selecting child rows:
```php
$posts = Post::whereExists(fn ($q) => $q->select(DB::raw(1))
->from('comments')->whereColumn('comments.post_id', 'posts.id')
->where('comments.approved', true))->get();
```
Use `selectRaw`/`whereRaw` with bindings, index join/filter columns, and inspect the query plan. Avoid string-concatenated SQL and correlated `whereIn` patterns that do unnecessary work.
Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.
No comments yet. Be the first to comment!