Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress Social Share Plugin powered by Ultimatelysocial