Not use that particular accessor. Just a good old regular method or create a getDiscountedPriceAttribute($value) method. Accessors don't have to have a corresponding database column.
Thanks shabushabu , but from the docs the getDiscountedPriceAttribute($val) method would need a 'discounted_price' column in the database to work wouldn't it? I am using the following Accessor to display the discounted price instead of the normal price:
public function getPriceAttribute($value) {
if (count ( $this->specials ) > 0) {//any specials that this model is related to??
foreach ( $this->specials as $s ) {//for all specials related to this object
if ($this->onSpecialNow ()) {//if its current....
return $value * $s->discount; // ....return the discounted price
} else {
return $value; // Otherwise return the normal price
}
}
} else {
return $value;//carry on as normal
}
}
This works fine for displaying, but when I want to edit a model in my admin it also displays the discounted value and, as such, gets saved as this manipulated discount price. I have managed to reverse the original process with a Mutator on the same Model, but is there a better way?
Bulmer said:
Thanks shabushabu , but from the docs the getDiscountedPriceAttribute($val) method would need a 'discounted_price' column in the database to work wouldn't it? I am using the following Accessor to display the discounted price instead of the normal price:
public function getPriceAttribute($value) { if (count ( $this->specials ) > 0) {//any specials that this model is related to?? foreach ( $this->specials as $s ) {//for all specials related to this object if ($this->onSpecialNow ()) {//if its current.... return $value * $s->discount; // ....return the discounted price } else { return $value; // Otherwise return the normal price } } } else { return $value;//carry on as normal } }
This works fine for displaying, but when I want to edit a model in my admin it also displays the discounted value and, as such, gets saved as this manipulated discount price. I have managed to reverse the original process with a Mutator on the same Model, but is there a better way?
You can create an accessor without the same field in the database. What you could do is this:
public function getDiscountedPriceAttribute()
{
$originalPrice = $this->price; // or $this->attributes['price']
// perform discount logic here
return $discountedPrice;
}
I often prefer to create my Accessors in this way so that I can always have access to the raw values coming out of the database.
Ok, thanks for clarifying that. Details are a bit thin in that Chapter of the docs....Cheers.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community