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

Coollection Laravel Package

pragmarx/coollection

Coollection repackages Laravel-style collections (via Tightenco\Collect) to let you access items as object properties. Traverse nested arrays/objects with fluent collection methods, then read values like $countries->where('name.common','US')->first()->currency->name.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require pragmarx/coollection
    

    This adds the coollect() helper and Coollection class to your project.

  2. First Use Case: Convert a standard array or Laravel Collection into a Coollection for object-like property access:

    $users = coollect([
        ['name' => 'John', 'age' => 30],
        ['name' => 'Jane', 'age' => 25]
    ]);
    
    // Access properties directly
    echo $users->first()->name; // "John"
    
  3. Key Features to Explore:

    • Dot Notation: Access nested arrays as properties ($collection->nested->key).
    • Case-Insensitive Keys: Use $collection->rio or $collection->RIO for keys like rio.
    • Laravel Collection Methods: Retain all Laravel Collection methods (e.g., where, filter, map).

Implementation Patterns

Common Workflows

  1. API Response Handling: Transform API responses (e.g., JSON) into Coollection for intuitive access:

    $response = coollect($apiResponse['data']);
    $user = $response->first()->profile->name; // Direct property chaining
    
  2. Request Data Processing: Convert Laravel request data into a Coollection for cleaner validation or manipulation:

    $input = coollect(request()->all());
    $pageSize = $input->pagination->perPage; // Instead of $input->get('pagination.perPage')
    
  3. Nested Data Filtering: Chain methods for complex queries:

    $filtered = $products
        ->where('category', 'electronics')
        ->sortBy('price')
        ->pluck('name')
        ->implode(', ');
    
  4. Dynamic Property Access: Use ia-str (dependency) for flexible key handling (snake_case, camelCase, etc.):

    $data->user_first_name; // Accesses 'user_first_name' or 'userFirstName'
    

Integration Tips

  • Replace collect(): Use coollect() instead of collect() for projects where object-like access is preferred.
  • Type Hinting: Use Coollection in method signatures for clarity:
    public function process(Coollection $data): Coollection { ... }
    
  • Laravel Service Providers: Register Coollection as a bindable interface if extending functionality:
    $this->app->bind(CollectionInterface::class, Coollection::class);
    

Gotchas and Tips

Pitfalls

  1. Key Sensitivity:

    • Keys are case-insensitive for single-word keys (e.g., $collection->rio or $collection->RIO).
    • Multi-word keys (e.g., user_name) require exact casing unless using ia-str utilities.
  2. Performance:

    • Property access is slower than array access ($collection['key']). Benchmark critical paths.
    • Avoid deep chaining in performance-sensitive loops (e.g., ->first()->nested->method()).
  3. Laravel Version Compatibility:

    • Requires Laravel 5.5+ (or standalone illuminate/collections).
    • Test with Laravel 10/11 due to dependency updates (e.g., illuminate/collections:^10.48|^11.29).
  4. Dot Notation Limitations:

    • Only works for array-like structures. Non-array values (e.g., null) will throw errors:
      $collection->non_existent->key; // Throws: "Property [non_existent] does not exist."
      

Debugging Tips

  • Check Existence: Use has() or contains() to verify keys before access:
    if ($collection->has('key')) {
        $value = $collection->key;
    }
    
  • Fallback to Array: Use $collection->toArray() to debug or fall back to standard methods:
    $value = $collection->get('key', $collection->toArray()['key'] ?? null);
    
  • IDE Support: Enable PHPStan or Psalm for better autocompletion (though IDEs may not recognize dynamic properties).

Extension Points

  1. Custom Property Access: Extend Coollection to add methods for domain-specific logic:
    class UserCollection extends Coollection {
        public function activeUsers() {
            return $this->where('status', 'active');
        }
    }
    
  2. Override Key Resolution: Use ia-str to customize key normalization (e.g., force snake_case):
    $collection = coollect([], ['key_case' => 'snake']);
    
  3. Standalone Usage: Instantiate without Laravel:
    use IlluminateExtracted\Support\Collection;
    $collection = new Collection(['data']);
    

Configuration Quirks

  • Global Defaults: Set defaults via config/coollection.php (if provided by the package) or environment variables:
    'default_key_case' => 'snake', // Forces snake_case for all collections
    
  • Helper Override: If coollect() conflicts, alias it in composer.json:
    "extra": {
        "aliases": {
            "coollect": "pragmarx/coollection:coollect"
        }
    }
    

```markdown
### Pro Tips
- **Combine with Laravel**:
  Use `Coollection` in Eloquent models for cleaner relationships:
  ```php
  $user->posts->published()->count(); // Instead of $user->posts()->where('published', true)->count()
  • Testing: Mock Coollection in tests with createMock(Coollection::class) for predictable behavior.
  • Legacy Code: Gradually replace collect() calls with coollect() using IDE refactoring tools.
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
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
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation