Reputation: 2624
This works, all posts are dumped with the votes
property set correctly (if it's null
then it's updated to have the value 0
):
$posts = Post::all();
foreach($posts as $post) {
$post->priority = $post->priority ?? 0;
}
dd($posts);
But if I do this I get an empty collection back:
$posts = Post::all();
$posts = $posts->map(function ($post) {
$post->priority = $post->priority ?? 0;
});
dd($posts);
From the docs it says that map
returns a new collection instance and that if you want to modify the existing collection you should use transform
, but that produces the same result.
Upvotes: 0
Views: 1387
Reputation: 15319
You should return after modifying data inside map
$posts = Post::all();
$posts = $posts->map(function ($post) {
$post->priority = $post->priority ?? 0;
return $post;
});
dd($posts);
As per doc
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:
Ref:https://laravel.com/docs/8.x/collections#method-map
Upvotes: 2