Framework: Model with array casting doesn't work when you update it

Created on 11 May 2017  路  5Comments  路  Source: laravel/framework

  • Laravel Version: 5.4.22
  • PHP Version: 7.0.15
  • Database Driver & Version: 5.6.35

Description:

Models with array casting works correctly when creating but not updating.

Steps To Reproduce:

Hi!
I have created a table with three columns:

  • id [INT]
  • name [VARCHAR]
  • json [VARCHAR]

the model corresponding to this table has a the follow casting

class Test extends Model
{
    protected $table        = 'test';
    protected $fillable     = ['id', 'name', 'json'];
    public $timestamps      = false;
    protected $casts        = [
        'json'    => 'array'
    ];
}

If I try execute a create command work perfectly:

Test::create([
            'name' => 'hello word',
            'json' => [
                'id' => 1,
                'data' => 'data 01'
            ]
        ]);

The json column contain a string with json data:

{"id":1,"data":"data 01"}

But if I try to update with update command:

Test::where('id', 1)->update([
            'name' => 'hello word',
            'json' => [
                'id' => 1,
                'data' => 'data 01'
            ]
        ]);

Get the follow error:

QueryException in Connection.php line 647:
Array to string conversion 

I need to parse array for update correctly:

Test::where('id', 1)->update([
            'name' => 'hello word',
            'json' => json_encode([
                'id' => 1,
                'data' => 'data 02'
            ])
        ]);

Should be able to update without json_encode if we have a casting? Just like when create element.
Thanks!

Most helpful comment

It's because you run update on Builder when casts is only Eloquent feature.
Use Test::find(1).

All 5 comments

It's because you run update on Builder when casts is only Eloquent feature.
Use Test::find(1).

Thanks!
but, what would be the best way to do it for mass assignment?
If you want change various records, there should be a way...

thanks!

This repo is for bug tracking. Use the forums or slack channel for solving your issue

@carlospalacin You can't update multiple Eloquent model at once I'm afraid.
Only select all of them, set values and save with foreach.
As @Dylan-DPC said you should close this issue and go to forums or Stack Overflow.

thanks @decadence

Was this page helpful?
0 / 5 - 0 ratings