0

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.

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

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.