Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

brandymedia's avatar

Optimising Eloquent Query with Relationship

I have ~500 users whom each have a new metrics row added to the DB each day.

I was running a query to find the difference between a value from their first entry and their last.

I decided to eager load the relationship to cut down on DB calls.

Something like...

$users = User::with('metrics')->get();

foreach ($users as $user) {
	$difference = $user->metrics->last()->value - $user->metrics->first()->value;
}

The problem with this approach is it loads all the user metrics models which is a drain on memory.

Is there a better approach to optimise the query?

0 likes
6 replies
brandymedia's avatar

@Sinnbeck thanks.

I tried...

$users = User::with(['latestMetric','oldestMetric'])->get();

foreach ($users as $user) {
	$difference = $user->latestMetric()->first()->followers_count - $user->oldestMetric()->first()->followers_count;
}

The page become unresponsive.

I'll have another play around with it.

brandymedia's avatar

@Sinnbeck

$user->latestMetric()->followers_count - $user->oldestMetric()->followers_count

Gives this error...

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$followers_count
brandymedia's avatar

@Sinnbeck

Changed to...

$user->latestMetric->followers_count - $user->oldestMetric->followers_count

I.e. without the parenthesis.

Looks like I'm in business.

Thanks for the help 👍

Please or to participate in this conversation.