How to get the latest and oldest record in Laravel Eloquent through ofMany.
Laravel ships with many awesome and time-saving methods for developers like us.. Here we will see some “One of Many” function’s examples:
Get the latest/last record from a model/relation
function latestRecord() {
return $this->hasOne(RelationModel::class)->latestOfMany();
}
Get the oldest/first record from a model/relation
function latestRecord() {
return $this->hasOne(RelationModel::class)->oldestOfMany();
}
Bonus!: Retrieve records with special conditions: in my case, max invoiced record
function mostInvoicedClient(){
return $this->hasOne(Invoice::class)->onMany(‘total_invoiced_amount’, ‘max’);
}
If this article helps you, then you can share this.. Thanks.
#HappyCoding #SharingIsCaring