Home > database >  Using latestOfMany() in Laravel
Using latestOfMany() in Laravel

Time:01-08

If I have a model called Placement which can have many PlacementTqLimit and I want to get the latest one, I'm assuming I can use this.

public function latestLimit()
{
    return $this->hasOne(PlacementTqLimit::class)->latestOfMany();
}

And then add a custom attribute to get the value

public function getLatestLimitValueAttribute()
{
    if (empty($this->latestLimit())) {
        return '100';
    }

    return $this->latestLimit()->value;
}

However, when I dump the $this->latestLimit() I'm getting a Illuminate\Database\Eloquent\Relations\HasOne... I'm sure I shouldn't have to call return $this->hasOne(PlacementTqLimit::class)->latestOfMany()->latest(). Am I doing something wrong here?

CodePudding user response:

$this->latestLimit() will return hasOne that extend query builder.

If you want to get the latest of PlacementTqLimit model just use $this->latestLimit without () or you can also use $this->latestLimit()->first()

So, to get the latest value limit, example code is:

public function getLatestLimitValueAttribute()
{
    if (!$this->latestLimit) {
        return '100';
    }

    return $this->latestLimit->value;
}
  •  Tags:  
  • Related