In Laravel PHP I have an object which needs some parameters updating. The object is updated and I can return or dd() the correct values. But when I ->save() its as if the values haven't been changed. The ->save method works fine, but the way I'm updating the object values is obviously wrong somehow...
So using the following code I loop through an array of parameters to update and create an updated object :
$account = Account::find('account_id');
// ^returns something like (object)['user'=>['name'=>'jeff','age'=>'20']];
$to_update = ['user.name':'john', 'user.age':'50'];
// the following function converts exploded arrays of key names to php objects
// ie user.name:"John" becomes user->name = john
function get($path, $object, $value) {
$temp = &$object;
foreach($path as $var) {
$temp =& $temp->$var;
}
$temp = $value;
}
// $account->user->name = "jim";
// $account->user->age = "100";
foreach($to_update as $keys => $value){
$key = explode(".", $keys);
get($key, $account, $value);
}
// $account->save();
return $account;
This returns a nice, updated object like :
+"user": +"name":"john" +"age":"50"
HOWEVER if I save that object, it doesn't save the updated values, only the old values. So changing the last two line :
$account->save();
return $account;
results in
+"user": +"name":"jeff" +"age":"20" // these are the old values
So my question is - why does return $account give the correct, updated object, but $account->save(); return $account revert to the original values?
FYI: the following code works (but is too simple for my purposes) :
$account = Account::find('account_id');
// ^returns something like (object)['user'=>['name'=>'jeff','age'=>'20']];
$account->user->name = "jim";
$account->user->age = "100";
$account->save();
return $account;
+"user": +"name":"jim" +"age":"100"
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire