Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Collection Laravel Package

phootwork/collection

phootwork/collection is a lightweight PHP collection library providing convenient data structures and fluent helpers to work with arrays and iterables. Includes common operations like map/filter/reduce, searching, sorting, and easy conversion between collection types.

View on GitHub
Deep Wiki
Context7

Getting Started

Start by installing via Composer: composer require phootwork/collection. The library provides first-class support for List, Set, Map, Queue, and Stack — each implementing PHP’s IteratorAggregate and offering a shared fluent API. Begin with the List collection, the most common type for ordered, index-based data:

use phootwork\collection\List as Collection;

$numbers = new Collection([1, 2, 3, 4, 5]);

// Chainable operations
$result = $numbers
    ->filter(fn($n) => $n % 2 === 0)
    ->map(fn($n) => $n * $n)
    ->toArray(); // [4, 16]

First use case: transforming form input arrays into domain-safe structures (e.g., validating and sanitizing request payloads into typed List<string> or List<int>).

Implementation Patterns

  • Pipeline-style data processing: Replace verbose foreach loops with expressive, testable chains (e.g., ->filter()->map()->reduce()).

  • Domain-driven value objects: Wrap API responses or database rows into List<Invoice>, Set<User>, or Map<string, Config> for type safety and consistency.

  • Pipeline composition: Build reusable collection pipelines as reusable methods or classes:

    class UserCollection
    {
        public static function fromArray(array $rows): Collection {
            return new Collection($rows)
                ->filter(fn($row) => $row['active'] ?? false)
                ->map(fn($row) => new User($row));
        }
    }
    
  • Early conversion guardrails: Convert at the edges (e.g., service boundaries) to avoid scattered array manipulations. Use ->toArray() or ->toIterable() only when returning from domain logic.

  • Integration with PSR-7/15: Transform PSR request bodies ($request->getParsedBody()) into collections for validation or mapping:

    $data = new Collection($request->getParsedBody());
    $validated = $data
        ->map(fn($v) => trim($v))
        ->filterKeys(fn($k) => in_array($k, ['email', 'name']));
    

Gotchas and Tips

  • Immutable by default: Most operations (map, filter, sort, etc.) return new collections — do not mutate in place. Chain carefully to avoid performance traps on large datasets.
  • Lossy iteration: Converting large collections to arrays via toArray() may exhaust memory. Consider ->toIterable() for lazy iteration or chunking with ->chunk(100).
  • Strictness matters: The library uses strict comparison (===) in contains(), unique(), and diff() — ensure types match (e.g., 1 vs '1').
  • Custom sorting: Use ->sort() with a comparison callback — but note it’s stable only in PHP 8.0+ (since 8.0+, usort is stable).
  • Memory optimization: For performance-critical loops, avoid repeated ->map()->filter() chains on large collections — consider consolidating operations or using generators where possible.
  • No generic constraints at runtime: PHP’s type system doesn’t enforce generics at runtime — validate collection contents before wrapping in typed collections.
  • Missing sum()? The library uses reduce() for aggregation — write $sum = $collection->reduce(fn($carry, $n) => $carry + $n, 0);. Use ->sum() if extended via a helper trait.
  • Debug tip: Use ->each(fn($item) => var_dump($item)) mid-chain to inspect intermediate state without breaking fluency.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4