Tuesday, March 7, 2017

Laravel Eloquent Json Column Updating Not Working

I'm using php 7 and MySQL 5.7. attributes field is defined as json column in my table.

I defined the casts in my model file.

protected $casts = ['attributes' => 'array'];

I don't have any problem adding data.

Transaction::create([

            'name'          => $this->name,
            'subject_id'    => $this->id,
            'subject_type'  => get_class($this),
            'attributes'    => ['status' => 0, 'type' => 'owner'],
            'user_id'       => $owner->id

        ]);

But I can not update the json data. I tried these methods:

$transaction = $this->transaction->where('content_key', $this->request->key)->first(); $transaction->update(['attributes->status' => 1]);

or

$transaction->attributes['status'] = 1; $transaction->save();

None work.

These methods work:

$transaction->update(['attributes'=> ['status' => 1, 'type' => 'owner'] ]);

(I need to update all data in this method)

or

Db::table('transactions')->where('content_key', $this->request->key)->update(['attributes->status' => '1'])

How can I do this with Eloquent?



via Gökhan YILDIZ

Advertisement