Laravel - Relationships - Has One Of Many

Sometimes 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 Order models, but you want to define a convenient way to interact with the most recent order the user has placed. You may accomplish this using the hasOne relationship type combined with the ofMany methods:

    
    /**
     * Get the user's most recent order.
     */
    public function latestOrder()
    {
        return $this->hasOne(Order::class)->latestOfMany();
    }
	

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

    
    /**
     * Get the user's oldest order.
     */
    public function oldestOrder()
    {
        return $this->hasOne(Order::class)->oldestOfMany();
    }
	

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. However, sometimes you may wish to retrieve a single model from a larger relationship using a different sorting criteria.

For example, using the ofMany method, you may retrieve the user's most expensive order. The ofMany method accepts the sortable column as its first argument and which aggregate function (min or max) to apply when querying for the related model:

    
    /**
     * Get the user's largest order.
     */
    public function largestOrder()
    {
        return $this->hasOne(Order::class)->ofMany('price', 'max');
    }
	
Because PostgreSQL does not support executing the MAX function against UUID columns, it is not currently possible to use one-of-many relationships in combination with PostgreSQL UUID columns.