0

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.

1 Answer 1

2

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

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.