Last active
December 23, 2017 02:55
-
-
Save abdumu/7f71d0d04abe7271d2de1a3a0178fe2d to your computer and use it in GitHub Desktop.
[Laravel] Improved version of Collection->map as a macro (you can add it at AppServiceProvider.php boot method)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Improved version of Collection->map method | |
* | |
* @param callable $callback | |
* | |
* @return Illuminate\Support\Collection | |
*/ | |
Illuminate\Support\Collection::macro('loop', function(callable $callback){ | |
$items = []; | |
$loop = (object) ['count' => count($this->items), 'index' => -1, 'iteration' => 0, 'remaining' => count($this->items)]; | |
foreach($this->items as $key => $item) { | |
$loop->index++; | |
$loop->iteration++; | |
$loop->remaining--; | |
$loop->first = $loop->index === 0; | |
$loop->last = $loop->index === $loop->count - 1; | |
$loop->even = ($loop->index + 1) % 2 === 0; | |
$loop->odd = ! $loop->even; | |
$items[$key] = $callback($item, $key, $loop); | |
} | |
return new static($items); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: