php - Indirect modification of overloaded property has no effect when I try to unset() from a multidimensional array
one text
Currently dealing with a multidimensional array here. I'm trying to search for a value and use that to delete an entire array for a like/unlike system similar to twitter.
$user->favs is a JSON column in my mysql db that handles likes.
Problem is that when I run unset(), it gives me
Indirect modification of overloaded property App\Models\User::$favs has no effect
my code:
if(!in_array($post->id, array_column($user->favs, 'post_id'))) {
$post->favs++;
$user->favs = array_merge($user->favs, $favs);
} else {
$post->favs--;
foreach($user->favs as $key => $value) {
if($value['post_id'] == $post->id) {
$tmp = $user->favs;
unset($tmp[$key]);
}
}
}
$user->save();
$tweet->save();
Edit: Solution to this problem in @lagbox's comment.
Explained in detail here, https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting
You have to set $user->keys
to $tmp
if($value['post_id'] == $post->id) {
$tmp = $user->favs;
unset($tmp[$key]);
$user->favs = $tmp
}
Source