Wednesday, March 15, 2017

Modifying a json Eloquent field specific value

I have a Notification object which extends from Model. This model has a data column where I am storing attempts apart from some extra data. The problem is that sometimes I need to modify this specific value. At the moment I am doing it this way:

public function incrementAttempts()
{
        $attempts = $this->data['attempts'];

        $this->data = array_merge($this->data, ['attempts' => ($attempts + 1)]);
}

If I want to update a specific value I need to re-store the whole json data with the modified value.

Is there some way to do something like this?

$this->data['attempts'] = $this->data['attempts'] + 1

I tried this but this error is returned

PHP error:  Indirect modification of overloaded property Notification::$data has no effect

UPDATE

I added this function that help me to get the value

public function getAttemptsAttribute()
{
    return $this->data['attempts'];
}

It would be awesome having this:

public function setAttemptsAttribute($value)
{
    $this->data['attempts'] = $value;
}



via Alan

Advertisement