Get min value of a relation using "with()"

35 Views Asked by At

I'm trying to get all my users that has a HasMany relation. I want to get the min value of column in relation and retrieve it with the user.

I'm trying this code, it works but it gives me all the model relation, not the one I'm looking for.

first() didn't work as well.

Any suggestion?

$users = User::with(['posts' => function($query) {$query->min('created_at');}])->get();
1

There are 1 best solutions below

0
Matthew Bradley On

We can use the setRelation method here to change how we are pulling back to the related post. Using the oldest method means we get the oldest post by the created_at field. This can be reversed using the latest method.

User::with('posts')->get()->map(function($user) {
    $user->setRelation('posts', $user->posts->oldest());
    return $user;
});