I have a customer model with many transactions, and I need to get customers only where the customer's latest transaction is < 5 years from now. So the result was a customer who had any transaction that matched the condition. Even the transaction that matched the condition is not the latest one.
public function lastTransaction()
{
return $this->hasOne(Transaction::class, 'user_id', 'id')->latest();
}
$customers = Customer::whereHas('lastTransaction', function ($q) {
$q->whereDate('created_at', '<', Carbon::now()->subYears(5));
})->get();