Change on laravel collection does not effect Change on laravel collection does not effect laravel laravel

Change on laravel collection does not effect


I tried some ways finally I found that unset() can solve the problem.

This code works:

$users=User::with('posts')->get();foreach($users as $user){    $posts=$user->posts->except($except_id);    unset($user->posts);    $user->posts=$post;}return $users;


You should probably do that as a query constraint in the with call instead, e.g. like this:

$users = User::with(['posts' => function($query) use ($except_id) {    $query->where('id', '!=', $except_id);}])->get();

Now you get all posts for all users except the posts with the id of $except_id, and you don't have to go through them afterwards to sort them out.