Models with array casting works correctly when creating but not updating.
Hi!
I have created a table with three columns:
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!
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
Most helpful comment
It's because you run update on Builder when casts is only Eloquent feature.
Use Test::find(1).