skip to Main Content

In laravel 11 / php 8.2 app I need to add several values to json value field of UserOption model
and I do it with code :

array_push($this->selectedCurrencies, array_values($userOption->value));
$userOption->value = array_values($this->selectedCurrencies);
$userOption->save();

But in value field I see new elements and subarray of old values, not flat array I need ?

How to fix it ?

2

Answers


  1. If the value field is a json to do what you want you need first to decode the value field from json to an array through json_decode. In addition it seems to me that what you are trying to do is to concatenate selectedCurrencies array with value array into a unique array and store it into the model.

    $valueArray = json_decode($userOption->value);
    $userOption->value = json_encode( $this->selectedCurrencies + 
    $valueArray);
    $userOption->save();
    

    I am using json_encode only if you want to save the new array as a Json. If you want an array you can avoid using json_encode.

    Not every model with a serialized json field will be designed to automatically decode the field every time it is retrieved. For example let’s imagine a situation in which the project on which you are working on has more types of requests that need to work with that field, such as AJAX calls for example that work better with a JSON. In this case it is not sure that you will have casts for this model. So Json_decode in this case is safer. You don’t risk to forget that the model has no casts for the JSON field of interest. On the other way if you start thinking every time that the decoding is automatic you are more vulnerable to errors such as not including json_decode for models that don’t have casts for the field you are working with.

    Login or Signup to reply.
  2. You’re supplying a single value as the second argument to array_push, which means the entire $userOption->value array is being appended as one value. I suggest you might want to expand it and add all the elements individually, eg using ...array_values($userOption->value):

    array_push($this->selectedCurrencies, ...array_values($userOption->value));
    $userOption->value = array_values($this->selectedCurrencies);
    $userOption->save();
    

    See https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search