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

Collect Laravel Package

tightenco/collect

A standalone port of Laravel’s Illuminate\Support\Collection for non-Laravel projects. Get expressive, chainable, higher-order methods like map, filter, reduce, pluck, groupBy, and more with minimal dependencies—ideal for any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require tightenco/collect
    

    No additional configuration is required—it’s a drop-in replacement for Laravel’s built-in Illuminate\Support\Collection.

  2. First Use Case Replace Laravel’s Collection with Tightenco\Collect\Collection in your code:

    use Tightenco\Collect\Collection;
    
    $items = collect([1, 2, 3]); // Now using Tightenco's Collection
    $doubled = $items->map(fn($item) => $item * 2);
    
  3. Where to Look First


Implementation Patterns

Core Workflows

  1. Data Transformation Use map, pluck, or transform for iterative data manipulation:

    $users = collect([
        ['name' => 'John', 'age' => 30],
        ['name' => 'Jane', 'age'  => 25],
    ]);
    $names = $users->pluck('name'); // ['John', 'Jane']
    $ages = $users->map(fn($user) => $user['age'] + 1); // [31, 26]
    
  2. Filtering and Searching Leverage filter, where, or reject for conditional logic:

    $activeUsers = $users->where('active', true);
    $adults = $users->filter(fn($user) => $user['age'] >= 18);
    
  3. Aggregation Use sum, avg, count, or groupBy for analytics:

    $totalAge = $users->sum('age'); // 55
    $groupedByAge = $users->groupBy(fn($user) => $user['age'] > 25 ? 'adult' : 'minor');
    
  4. Chaining and Fluency Chain methods for concise, readable pipelines:

    $result = $users
        ->where('active', true)
        ->pluck('name')
        ->sort()
        ->values();
    
  5. Integration with Laravel

    • Eloquent: Replace Model::all() collections:
      use Tightenco\Collect\Collection;
      $posts = Post::all(); // Now returns Tightenco\Collect\Collection
      
    • Blade: Pass collections directly to views (no template changes needed).
  6. Custom Collections Extend Tightenco\Collect\Collection for domain-specific logic:

    class UserCollection extends \Tightenco\Collect\Collection {
        public function activeOnly() {
            return $this->where('active', true);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Method Differences

    • Some Laravel-specific methods (e.g., forPage(), macro()) may behave differently or be missing. Verify against Laravel’s Collection docs.
    • Example: macro() is not supported in tightenco/collect—use traits or custom classes instead.
  2. Performance

    • Avoid over-chaining methods in loops (e.g., foreach + collect()->where()). Pre-filter data when possible.
    • Tip: Use tap() to debug intermediate steps without breaking the chain:
      $users->tap(fn($c) => dump($c))->where('active', true);
      
  3. Serialization

    • Collections serialize differently than arrays. Use toArray() explicitly when passing to APIs or storage:
      $json = json_encode($collection->toArray());
      
  4. Compatibility

    • Laravel Mixins: If using Laravel’s Collection mixins (e.g., Str::limit()), they won’t work here. Reimplement or use native PHP functions.
    • Third-Party Packages: Some packages assume Laravel’s Collection class. Test thoroughly after swapping.

Debugging

  1. Dump Methods Use dump() or dd() (from Laravel’s Illuminate\Support\Facades) for inspection:

    use Illuminate\Support\Facades\Dump;
    Dump::collect($collection); // Pretty-prints the collection
    
  2. Type Checking Verify the collection class at runtime:

    if ($collection instanceof \Tightenco\Collect\Collection) {
        // Custom logic for Tightenco's Collection
    }
    

Extension Points

  1. Custom Macros Add static methods to the Collection class via a trait or helper:

    \Tightenco\Collect\Collection::macro('snakeKeys', function () {
        return $this->mapWithKeys(fn($item) => [
            Str::snake(key($item)) => $item,
        ]);
    });
    
  2. Global Replacement Override Laravel’s Collection facade in config/app.php:

    'aliases' => [
        'Collect' => Tightenco\Collect\Facades\Collect::class,
    ],
    

    Note: This may conflict with other packages. Use cautiously.

  3. Performance Optimizations

    • For large datasets, use each() instead of map() if you don’t need the results:
      $collection->each(fn($item) => $item->process());
      
    • Pre-load relationships in Eloquent to avoid N+1 queries before converting to a collection.

Config Quirks

  • No Configuration File: tightenco/collect has no settings—it’s a pure drop-in.
  • Environment Awareness: If using Laravel’s config(), ensure your app’s environment is loaded before collection operations.

Pro Tips

  1. Immutable Operations Prefer map() over direct array manipulation for predictability:

    // Bad: Mutates the original
    $collection->all['key'] = 'value';
    
    // Good: Returns a new collection
    $collection->put('key', 'value');
    
  2. Lazy Loading Use lazy() for large datasets to defer execution:

    $lazy = $users->lazy()->map(fn($user) => $user->load('posts'));
    
  3. Testing Mock collections in PHPUnit with createCollection():

    $mock = \Tightenco\Collect\Collection::make([1, 2, 3]);
    $this->assertEquals([2, 4, 6], $mock->map(fn($i) => $i * 2));
    
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
milesj/emojibase
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