What’s the difference between map() and mapSpread() Eloquent Collection’s

Asked

Viewed 68 times

1

I’ve had the eloquent for a while, but I’ve read the documentation and I can’t understand the difference between the method map() and mapSpread(), there are other methods with 'Spread' in the name, someone would have an example ?

1 answer

0


Collection::map(callable $callback): Collection

Run a map over each of the items.

The method map will iterate over each item of the array, applying the $callback and returning a new value to the item, placing each of the values generated by $callback in a new Collection and returning this Collection.

Example of Collection for use with map:

Collection([item1, item2, ...])

The Collection::map can be compared to Array.map javascript.

Collection::mapSpread(callable $callback): Collection

Run a map over each nested Chunk of items.

The mapSpread do basically the same thing, but with one difference, he hopes to work on top of a Collection of two levels, as a array of arrays and, instead of applying the $callback in each direct child (first level), it will open (in English spread) each of the direct children, who are of the type Collection, and will apply the $callback in each of the direct children of each Collection that is opened. Again the value returned for each execution of $callback will be stored in a new Collection which will be returned at the end of the execution of the method.

Example of Collection for use with mapSpread:

Collection([
    Collection([item1, item2, ...])
    Collection([item1, item2, ...])
    Collection([item1, item2, ...])
    Collection([item1, item2, ...])
    Collection([...])
    ...
])

The Collection::mapSpread can be compared to Array.flatMap javascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.