Modify a custom attribute of an Eloquent Model
12,995
The problem is that your accessor returns always 1
public function getCounterAttribute()
{
return 1;
}
Your loop sets correctly the counter
attribute (inspectable via $model->attributes['counter']
).
However, when you call $test->counter
its value is resolved via the getCounterAttribute()
method, that returns always 1.
Update your getCounterAttribute()
to something like this:
public function getCounterAttribute()
{
return isset($this->attributes['counter']) ? $this->attributes['counter'] : 1;
}
this way, you are saying: "if the counter attribute is set, return it. Otherwise, return 1".
Author by
Lucian P.
Updated on July 30, 2022Comments
-
Lucian P. over 1 year
I have a model which contain a custom attribute
class Test extends Model { protected $appends = ['counter']; public function getCounterAttribute() { return 1; } }
I need to change the value of the custom attribute, like:
$tests = Test::all(); foreach ($tests AS $test) { $test->counter = $test->counter + 100; }
This does not work, which is the correct way to do it?