Take a look at this article
https://reinink.ca/articles/dynamic-relationships-in-laravel-using-subqueries
And instead of first() have you tried to limit it to one, for example:
$query->latest()->take(1);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi! When I run this query :
User::
with(['comments' => function ($query) {
$query->latest();
},'department'])
->whereHas('comments', function (Builder $query) {
$query->where('from_id', auth()->user()->id)
->orWhere('to_id', auth()->user()->id);
})
->get();
I get an array of Users where the first User has 3 comments. But when add first() after latest() like so:
User::
with(['comments' => function ($query) {
$query->latest()->first();
},'department'])
->whereHas('comments', function (Builder $query) {
$query->where('from_id', auth()->user()->id)
->orWhere('to_id', auth()->user()->id);
})
->get();
First User has an empty array of comments. Also if I try to get only one User like so:
User::
with(['comments' => function ($query) {
$query->latest()->first();
},'department'])
->whereHas('comments', function (Builder $query) {
$query->where('from_id', auth()->user()->id)
->orWhere('to_id', auth()->user()->id);
})
->first();
Last comment is present. I dont understand such behaviour. What am I doing wrong? Please help
You will learn to ignore @munazzil
I see you totally changed the query?
You should be able to create a new relationship on the user model for latest comment which is a hasOne type.
Test this on its own first
Please or to participate in this conversation.