Reputation: 399
I have a user model, with a profile_details column which holds a json_encoded object of the user profile information. The object is as shown below
$user->profile_details: {
'name' : 'Wayne',
'books' : [
{ id: 1, title : 'Rich Dad' , isbn: 9780},
{ id: 3, title : 'Business school' , isbn: 8891}
]
}
How do I modify the value of the 'id' property of the books array after retrieving the user model from the database.
Below is what I have tried.
$user =User::find(1);
$newBooks = array();
if($user) {
$profile_details_decoded = json_decode($user->profile_details) ;
foreach($profile_details_decoded->books as $book) {
$book->id = 28;
array_push($newBooks, $book);
}
$user->profile_details->books = $newBooks;
}
dd($user->profile_details->books);
I expected the $newBooks
array to replace the $user->profile_details->books
array.
Please someone should kindly guide me. Thanks.
Upvotes: 0
Views: 2325
Reputation: 494
Since profile_details
hold json_encoded data, you have to work on the copy of the array and assign the array completely to the column.
$profile_details_decoded = json_decode($user->profile_details);
$newBooks = [];
foreach($user->profile_details->books as $book) {
$book->id = 28; // whatever logic you want fpr changing id
$newBooks[] = $book;
}
$profile_details_decoded->books = $newBooks
$user->profile_details = $profile_details_decoded;
Upvotes: 1