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?

+3


source to share


3 answers


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();

      

0


source


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.

+2


source


You can access your json keys with an arrow so you can update the column like this:

Flight::where('id', $id)->update([
   'destinations->from' => $data['from'],
   'destinations->to'  => $data['to']
]);

      

As @fubar mentioned, you must have mysql 5.7 for my solution to work.

check docs

+1


source







All Articles