DEV Community

Morcos Gad
Morcos Gad

Posted on

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();
}
Enter fullscreen mode Exit fullscreen mode
// Get Oldest Browser History
public function oldestBrowserHistory(){
    return $this->hasOne(BrowserHistory::class)->oldestOfMany();
}
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Top comments (0)