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.
Top comments (0)