DalekSall
DalekSall

Reputation: 385

Do a calculation before returning attribute in Laravel

Is it possible to change an attribute before it's value is returned in Laravel?

I have 2 ways of finding a sell price, the one implemented is just getting the price from the database, and the other is calculating it from a buy price with currency and advance.

Throughout the system i pull the price like this:

$product->baseprice;

Is it possible to run a model function like this:

public function baseprice(){
    if(is_null($this->baseprice){
       return $this->calculatePrice();
    }
    return $this->baseprice;
} 

It's always one way or the other, baseprice will always be null if the sellprice should be calculated. when using $this->baseprice? Comments are welcome if this is bad practice.

Upvotes: 0

Views: 2145

Answers (2)

alexrussell
alexrussell

Reputation: 14202

What you're looking for is an accessor. The Laravel documentation has plenty of good examples on how to use these, but in a nutshell you define a method in the form get[Whatever]Attribute and it allows you to call $model->whatever and get the output of that method.

So, your code will be something like this:

public function getBasepriceAttribute()
{
    if (is_null($this->attributes['baseprice'])) {
        return $this->calculatePrice();
    }

    return $this->attributes['baseprice'];
}

Upvotes: 3

Adiasz
Adiasz

Reputation: 1804

You can change an attribute before it's value is returned from model by Accessors

Upvotes: 1

Related Questions