1

I have data in MySQL db, table 'user', column 'attributes' with json type as follow :

{"hp": {"remaining": 10, "total": 10}, "mp": {"remaining": 5, "total": 5}}

I want to update hp->remaining to 9 without updating the whole json but just the key

1st method :

$user = Users::find(1)->firstOrFail();
$user->attributes->hp->remaining = 9;
$user->save();

it failed saying Indirect modification of overloaded property App\Models\Users::$attributes has no effect

2nd method :

$user = Users::find(1)->firstOrFail();
$user->attributes = json_encode(array('hp' => array('remaining' => 9)));
$user->save();

it didn't have any errors but it failed because it updated the whole json attributes and lost 'hp->total' key and all mp, thus became

{"hp": {"remaining": 9}}

I know I can just replace the whole json with updated key like:

$user = Users::find(1)->firstOrFail();
$user->attributes = json_encode(array(
                                      'hp' => array('remaining' => 9, 'total' => 10), 
                                      'mp' => array('remaining' => 5, 'total' => 5)
                                     ));
$user->save();

However is there a way to update just the key?

3
  • decode the json string to an array and then update the query.. Commented Jul 7, 2016 at 14:00
  • you can't. json is a container format, and should never be manipulated directly. decode a native structure, change any values you want, then re-encode to json. anything else risks corrupting the json. Commented Jul 7, 2016 at 14:11
  • not forget to choose approved answer by click on gray "check" on its left side Commented Aug 2, 2018 at 8:55

3 Answers 3

1
$str = '{"hp": {"remaining": 10, "total": 10}, "mp": {"remaining": 5, "total":      5}}';
$array=json_decode($str,true);
$array['hp']['remaining'] = 9;
$result = json_encode($array);
echo $result;
result is {"hp":{"remaining":9,"total":10},"mp":{"remaining":5,"total":5}}
hope use for you...
Sign up to request clarification or add additional context in comments.

Comments

1

This should do the work (laravel 5.5)

$data = $user->attributes;
$data['hp']['remaining'] = 9;
$user->attributes = $data;
$user->save();

Comments

0
$user = Users::find(1)->firstOrFail();

$decode = json_decode($user,true); //use as an array
$uid = $decode["id"];
$remaining = $decode["hp"]["remaining"];
$remaining1 = $decode["mp"]["remaining"];
$encode_remaining = json_encode($remaining);
$encode_remaining1 = json_encode($remaining1);

$db = User::where("id","=",$uid)->update([$encode_remaining=> 9 , $encode_reamaining1 => 5]);

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.