pwnz22 pwnz22 - 2 months ago 11
PHP Question

$casts, array data

I'm using $casts to save data in array to database. I have an issue with that.

How can i push data to an existing array in the database?
For example i have already an array of data in my db column like:

["some_data", "another_el"]
and so on and in the Controller i want to push in this array in db some other data from input.

$brand = Brand::find($request->input('brand'));

$brand->model = $request->input('model');
$brand->update();


Pushing data like this.

Answer

You cannot do this with Eloquent's Mass Assignment functions (update, create, etc). You must pull down your field, change it, then save the model.

$collection = collect($brand->field);
$collection->push($myNewData);
$brand->field = $collection->toJson();
$brand->save();