Gökhan YILDIZ
Gökhan YILDIZ

Reputation: 141

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?

Upvotes: 1

Views: 1271

Answers (1)

cartbeforehorse
cartbeforehorse

Reputation: 3487

So having experienced the same problem as you, I took a day to figure out what was going on under the hood. Try this on for size:

$transaction->setAttribute ('attributes->status', 1);

If you ask me, Laravel's documentation is seriously lacking in detail on the subject! (But then I suppose that's just a standard feature of Laravel).

Upvotes: 2

Related Questions