Larvel eloquent doesn't update JSON column: array to string conversion
I want to update a JSON column in my database, but I am getting this error:
Array to string conversion
I declared the column name as array
in the model:
protected $casts = [
'destinations' => 'array'
];
this is the code i am using:
$data[] = [
'from' => $fromArray,
'to' => $toArray
];
Flight::where('id', $id)->update(['destinations' => $data]);
What should I do?
source to share
Consistent with this Github talk: Make json attributes populate when the model field is populated Taylor Otwell recommends using the method save
:
$ model-> options = ['foo' => 'bar'];
$ models-> Save ();
So, in this case, you can do it like this:
$flight = Flight::find($id); $flight->destinations = $data; $flight->save();
source to share
You are getting this error because you are trying to update your model with Query Builder, which basically just generates raw SQL queries. It is unaware of the data casting, etc., defined in your model. Therefore, you have three options:
1) Find your model and run update on the model instance.
$flight = Flight::findOrFail($id);
$flight->update(['destinations' => $data]);
2) Convert the data to string before updating.
$data = json_encode($data);
Flight::where('id', $id)->update(['destinations' => $data]);
3) Use a database that supports JSON column queries as suggested by @AmrAly. Beware of this option as not all databases support JSON columns.
source to share