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

atournayre/collection

Type-safe PHP collections with list/map factories, plus immutable variants. Includes DecimalValue collections with consistent precision handling. Build domain-specific collections by extending TypedCollection to enforce item types and safe manipulation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require atournayre/collection
    

    No service provider or facade needed—use it as a standalone utility.

  2. First Use Case:

    use ATournayre\Collection\Collection;
    
    $items = ['apple', 'banana', 'cherry'];
    $collection = new Collection($items);
    
    // Basic filtering
    $fruitsWithA = $collection->filter(fn($item) => str_starts_with($item, 'a'));
    // Returns: ['apple']
    
  3. Where to Look First:

    • Source Code (if available) for advanced methods.
    • Collection class docs (if any) or PHPDoc comments in the codebase.
    • Laravel’s built-in Illuminate\Support\Collection for comparison (similar API).

Implementation Patterns

Common Workflows

  1. Chaining Methods:

    $result = $collection
        ->filter(fn($item) => strlen($item) > 5)
        ->map(fn($item) => strtoupper($item))
        ->sort();
    
  2. Integration with Laravel:

    • Replace collect() calls where custom logic is needed:
      $users = User::all();
      $activeAdmins = (new Collection($users))
          ->where('is_admin', true)
          ->where('active', true);
      
  3. Custom Logic:

    • Extend the Collection class for domain-specific methods:
      class UserCollection extends Collection {
          public function activeAdmins() {
              return $this->where('role', 'admin')->where('active', true);
          }
      }
      
  4. Data Transformation:

    • Use transform() or map() for nested structures:
      $posts = (new Collection($posts))
          ->map(fn($post) => [
              'title' => $post->title,
              'author' => $post->user->name,
          ]);
      
  5. Performance Considerations:

    • Prefer each() for side-effects (avoids creating new collections):
      $collection->each(fn($item) => Log::info($item));
      

Gotchas and Tips

Pitfalls

  1. Lazy Loading:

    • Methods like filter() or map() return new collections, not modified instances. Avoid chaining if memory is a concern:
      // Bad: Creates 3 intermediate collections
      $result = $collection->filter()->map()->sort();
      
  2. Type Safety:

    • No built-in type hints in the package. Validate inputs manually:
      $collection = new Collection($items); // $items must be iterable
      
  3. Laravel Collision:

    • If using Laravel, avoid naming conflicts by aliasing:
      use ATournayre\Collection\Collection as CustomCollection;
      
  4. Undocumented Methods:

    • Some methods may not be documented. Check the source for:
      • chunk(), collapse(), or flatten() (if available).
      • Custom methods like pluck() (compare with Laravel’s pluck()).

Debugging Tips

  1. Inspect Collections:

    $collection->dump(); // Uses Laravel’s dump() if available
    // Fallback:
    print_r($collection->all());
    
  2. Common Errors:

    • InvalidArgumentException: Pass non-iterable data to the constructor. Fix: Use array() or collect() first.
    • Method Not Found: Check for typos (e.g., forelse vs. foreach).

Extension Points

  1. Macros: Add reusable methods globally:

    Collection::macro('firstWhereIn', function ($key, $values) {
        return $this->firstWhere($key, fn($val) => in_array($val, $values));
    });
    
  2. Custom Comparators: Override equals() for deep comparison:

    class DeepCollection extends Collection {
        public function equals($collection) {
            return $this->all() === $collection->all();
        }
    }
    
  3. Integration with Laravel Events:

    Collection::macro('trigger', function ($event) {
        event(new \App\Events\CollectionProcessed($this));
    });
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle