Reputation: 385
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
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