Laravel One of Many Eloquent Relationship Example

  Laravel Published:  1 year ago
Laravel One of Many Eloquent Relationship Example - TechvBlogs

A new one of many  Eloquent relationships is coming to Laravel 8.42 thanks to a PR contribution by Lennart Carstens-Behrens along with collaboration from Taylor Otwell is released some days ago. This one of many relationships is very useful.

So what is one of many relationships is? The one-of-many relationship creates a one-to-one association from a one-to-many relationship. This quote is not enough to define this relationship. So let's see an example to understand.

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.

You may accomplish this using the  hasOne relationship type combined with the  ofMany methods:

// Get Latest Browser History

public function latestBrowserHistory(){
    return $this->hasOne(BrowserHistory::class)->latestOfMany();

Read Also:   API Authentication using Laravel Sanctum

You may define a method to retrieve the "oldest", or first, related model of a relationship:

// Get Oldest Browser History

public function oldestBrowserHistory(){
    return $this->hasOne(BrowserHistory::class)->oldestOfMany();

Here in this query by default, the  latestOfMany and  oldestOfMany methods will retrieve the latest or oldest related model based on the model's primary key, which must be sortable.

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');

Thank you for reading this blog.

Read Also:   Firebase Push Notification Laravel Tutorial

If you have any queries or doubts about this topic please feel free to  contact us . We will try to reach you.

Laravel PHP

Comments (0)

No Comments Found.