简体   繁体   中英

Appending data to an object JSON field using json_encode/decode transforms my array into an int Laravel

So I have a class "File" that has a field "file_history" in JSON, and in my CRUD operations on Laravel I'd like to append some JSON values to this field, for instance, when I'm creating my File object in my database, I first have {"created_at": "2022-07-18"} in my file_history field. And then if I update my object I would now have:

{
    "created_at": "2022-07-18"
},
{
    "updated_at": "2022-07-08"
}

So I first thought about transforming my initial JSON values from my previous CRUD operations on the object into an array, append the new JSON values to this array, and then encode my array again into JSON. This is the code I wrote:

public function update(Request $request, String $uuid)
{
    $file = File::find($uuid);

    $json_data = array(
        "updated_at" => Carbon::now()
    );

    $file_history = json_decode($file->file_history, true);
    $file_history = array_push($file_history, $json_data);

    $file->file_history = json_encode($file_history);

    $file->update($request->all());
    return $file;
}

But using that code, I now have "2" in my database in my file_history field... I don't have JSON or anything else, just this 2 even if my field is categorized as JSON. Any idea why and how to fix this? Thanks

You have "2" in your database, because array_push function returns the new number of elements in the array. So your code shoud be like this:

$file_history = json_decode($file->file_history, true);
array_push($file_history, $json_data);

$file->file_history = json_encode($file_history);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM