Created
March 29, 2024 11:42
-
-
Save VivienLN/17161cd379b3f7ae8c054dfc734bcd4f to your computer and use it in GitHub Desktop.
Laravel collection::ellipsis
This file contains hidden or 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 | |
| // AppServiceProvider::boot() | |
| /** | |
| * Returns a collection with max $limit entries. Other entries are grouped in the last item if needed. | |
| * | |
| * @param int $limit | |
| * @param callable(Illuminate\Support\Collection): Mixed $lastCallback | |
| * | |
| * @return int | |
| */ | |
| Collection::macro('ellipsis', function (int $limit, callable $lastCallback) { | |
| // If collection not exceeding $limit, return it as-is | |
| if($this->count() <= $limit) { | |
| return $this; | |
| } | |
| // To show X element in final output, we need to take X-1 of original collection (Xth being the "others" entry) | |
| $limit--; | |
| $others = $this->skip($limit); | |
| return $this | |
| ->take($limit) | |
| ->push($lastCallback($others)); | |
| }); | |
| // Example usage | |
| // (Will return 9 first projects, and a last "others" with the number of other projects) | |
| $projects->sortByDesc('updated_at')->ellipsis(10, function($others) { | |
| return ['others' => $others->count()]; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment