Laravel One of Many Eloquent Relationship (latestOfMany – oldestOfMany – ofMany)

Eloquent relationships is coming to Laravel 8.42
Many times you will see that a model may have many related models, yet you want to easily retrieve the “latest” or “oldest” related model of the relationship. For example, a User model may be related to many BrowserHistory models.

// Get Latest Browser History
public function latestBrowserHistory(){
    return $this->hasOne(BrowserHistory::class)->latestOfMany();
// Get Oldest Browser History
public function oldestBrowserHistory(){
    return $this->hasOne(BrowserHistory::class)->oldestOfMany();

This new eloquent relationship ofMany the method accepts the sortable column as its first argument and which aggregate function ( min or max) to apply when querying for the related model

public function highestPriceProduct(){
    return $this->hasOne(Product::class)->ofMany('price','max');

I hope you enjoyed the code.

Source: DEV Community

December 2, 2021
Category : News
Tags: beginners | laravel | php | programming

Leave a Reply

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

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.