Skip to main content

Collection

The Ecommerce\Core\Collections\Collection class provides a fluent wrapper around arrays of data. It is used extensively by the Query Builder to return results and offers a wide variety of methods for filtering, mapping, and transforming data.

Introduction​

Reflecting the functionality of Laravel's Collections, this class allows you to chain methods to process data efficiently. All Query Builder methods that retrieve multiple records return an instance of Collection.

Creating Collections​

Create New Collection​

Create a new collection instance from an array of items.

Description:

The constructor initializes a new Collection instance with the provided array of items. These items can be simple values, arrays, or objects (like Model instances).

Method Signature:

public function __construct(array $items = [])

Parameters:

  • $items - (Optional) The array of items to initialize the collection with.

Examples:

use Ecommerce\Core\Collections\Collection;

// Create from a simple array
$collection = new Collection([1, 2, 3]);

// Create from Model instances
$products = new Collection([
Product::find(1),
Product::find(2)
]);

Create Range​

Create a collection from a range of numbers.

Description:

The range() static method creates a new collection containing a sequence of integers.

Method Signature:

public static function range(int $start, int $end, int $step = 1): static

Parameters:

  • $start - The starting value of the range.
  • $end - The ending value of the range.
  • $step - (Optional) The increment step. Defaults to 1.

Examples:

// Create a collection: [1, 2, 3, 4, 5]
$numbers = Collection::range(1, 5);

// Create with step: [0, 10, 20, 30]
$steps = Collection::range(0, 30, 10);

Retrieving & Inspecting Items​

Get All Items​

Retrieve the underlying array of items.

Description:

The all() method returns the raw array of items stored in the collection.

Method Signature:

public function all(): array

Examples:

$collection = new Collection([1, 2, 3]);
$array = $collection->all(); // [1, 2, 3]

Get First Item​

Get the first item in the collection.

Description:

The first() method returns the first element in the collection. If the collection is empty, it returns null.

Method Signature:

public function first(): mixed

Examples:

$products = Product::where('active', 1)->get();
$firstProduct = $products->first();

if ($firstProduct) {
echo $firstProduct->name;
}

Get Last Item​

Get the last item in the collection.

Description:

The last() method returns the last element in the collection. If the collection is empty, it returns null.

Method Signature:

public function last(): mixed

Examples:

$orders = Order::all();
$latestOrder = $orders->last();

Count Items​

Get the total number of items in the collection.

Description:

The count() method returns the integer count of items. The collection also implements the Countable interface, so you can use count($collection).

Method Signature:

public function count(): int

Examples:

$products = Product::where('category', 'electronics')->get();
$count = $products->count();

echo "Found {$count} products.";

Check if Empty​

Determine if the collection is empty.

Description:

The is_empty() method returns true if the collection contains no items, and false otherwise.

Method Signature:

public function is_empty(): bool

Examples:

$cart = new Collection([]);

if ($cart->is_empty()) {
echo "Your cart is empty.";
}

Check if Not Empty​

Determine if the collection has items.

Description:

The is_not_empty() method returns true if the collection contains at least one item.

Method Signature:

public function is_not_empty(): bool

Examples:

$orders = Order::where('status', 'pending')->get();

if ($orders->is_not_empty()) {
echo "You have pending orders.";
}

Check Containment​

Determine if the collection contains a given value.

Description:

The contains() method checks if a value exists in the collection. You can also pass a closure to check if any item passes a truth test.

Method Signature:

public function contains(mixed $value, bool $strict = false): bool

Parameters:

  • $value - The value to check for, or a closure function($item, $key).
  • $strict - (Optional) Whether to use strict comparison (===). Defaults to false.

Examples:

$ids = new Collection([1, 2, 3]);
$hasTwo = $ids->contains(2); // true

// Using a closure
$products = Product::all();
$hasExpensiveItem = $products->contains(function ($product) {
return $product->price > 1000;
});

Modifying & Transforming​

Map Items​

Transform each item in the collection.

Description:

The map() method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, forming a new collection of modified items.

Method Signature:

public function map(callable $callback): static

Parameters:

  • $callback - A callable function($item, $key) that returns the new value.

Examples:

$products = Product::all();

$productNames = $products->map(function ($product) {
return $product->name;
});

Filter Items​

Filter items using a callback.

Description:

The filter() method filters the collection using the given callback, keeping only those items where the callback returns true. If no callback is provided, it removes all empty values.

Method Signature:

public function filter(callable $callback = null): static

Parameters:

  • $callback - (Optional) A callable function($item, $key) that returns a boolean.

Examples:

$products = Product::all();

$activeProducts = $products->filter(function ($product) {
return $product->status === 'active';
});

// Without callback (removes null/false/empty)
$collection = new Collection([1, null, 2, false, 3]);
$filtered = $collection->filter(); // [1, 2, 3]

Reject Items​

Reject items using a callback.

Description:

The reject() method is the inverse of filter. It removes items where the callback returns true.

Method Signature:

public function reject(callable $callback = true): static

Parameters:

  • $callback - A callable function($item, $key) that returns a boolean.

Examples:

$products = Product::all();

$outOfStock = $products->reject(function ($product) {
return $product->stock > 0;
});

Pluck Values​

Get specific values from all items.

Description:

The pluck() method retrieves all of the values for a given key or property from the items in the collection.

Method Signature:

public function pluck(string $column): static

Parameters:

  • $column - The key or property name to extract.

Examples:

$products = Product::all();

// Get a collection of all product names
$names = $products->pluck('name');

// Get a collection of all product IDs
$ids = $products->pluck('id');

Push Items​

Add items to the end of the collection.

Description:

The push() method appends one or more items to the end of the collection.

Method Signature:

public function push(...$values): static

Parameters:

  • ...$values - Variable number of items to add.

Examples:

$ids = new Collection([1, 2]);
$ids->push(3, 4); // [1, 2, 3, 4]

Merge Collections​

Merge items with another array or collection.

Description:

The merge() method merges the given array or collection with the original collection.

Method Signature:

public function merge(mixed $items): static

Parameters:

  • $items - An array or Collection to merge.

Examples:

$collection1 = new Collection(['a', 'b']);
$collection2 = ['c', 'd'];

$merged = $collection1->merge($collection2); // ['a', 'b', 'c', 'd']

Only Keys​

Get items with specific keys.

Description:

The only() method returns a new collection consisting of the items with the specified keys.

Method Signature:

public function only(mixed $keys): static

Parameters:

  • $keys - A single key or an array of keys to keep.

Examples:

$data = new Collection([
'product_id' => 1,
'name' => 'Desk',
'price' => 100,
'discount' => 10
]);

$summary = $data->only(['name', 'price']);
// ['name' => 'Desk', 'price' => 100]

Sort Items​

Sort the collection.

Description:

The sort() method sorts the collection. You can provide a custom callback for sorting logic, or let it sort naturally.

Method Signature:

public function sort(callable $callback = null): static

Parameters:

  • $callback - (Optional) A comparison function function($a, $b).

Examples:

$prices = new Collection([10, 5, 20]);
$sorted = $prices->sort(); // [5, 10, 20]

$products = Product::all();
$sortedProducts = $products->sort(function ($a, $b) {
return $a->price <=> $b->price;
});

Flatten Array​

Collapse a collection of arrays into a single, flat collection.

Description:

The collapse() method collapses a collection of arrays into a single, flat collection.

Method Signature:

public function collapse(): static

Examples:

$collection = new Collection([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]);

$collapsed = $collection->collapse();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Aggregates​

Sum Values​

Get the sum of the items.

Description:

The sum() method returns the sum of all items in the collection. If a key or callback is provided, it sums the values returned by that key/callback.

Method Signature:

public function sum(callable $callback = null): int|float

Parameters:

  • $callback - (Optional) A callable to extract values to sum.

Examples:

$orders = Order::all();

// Sum of order totals (if collection was simple numbers)
// $total = $amounts->sum();

// Sum via callback
$totalRevenue = $orders->sum(function ($order) {
return $order->total_amount;
});

Average Values​

Get the average of the items.

Description:

The avg() (alias for average()) method returns the average value of the items.

Method Signature:

public function avg(callable $callback = null): float

Parameters:

  • $callback - (Optional) A callable to extract values to average.

Examples:

$reviews = Review::where('product_id', 1)->get();

$averageRating = $reviews->avg(function ($review) {
return $review->rating;
});

Min/Max Values​

Get the minimum or maximum value.

Description:

The min() and max() methods return the minimum and maximum values in the collection, respectively.

Method Signature:

public function min(callable $callback = null): mixed
public function max(callable $callback = null): mixed

Parameters:

  • $callback - (Optional) A callable to extract values for comparison.

Examples:

$products = Product::all();

$minPrice = $products->min(fn($p) => $p->price);
$maxPrice = $products->max(fn($p) => $p->price);

Conditionals​

The Collection class uses the Conditionable trait, offering conditional method chaining.

When True​

Execute a callback if a condition is true.

Description:

The when() method will execute the given callback if the first argument evaluates to true.

Method Signature:

public function when(mixed $value, callable $callback, mixed $default = null): mixed

Parameters:

  • $value - The condition to check.
  • $callback - Executed if true: function($collection, $value).
  • $default - (Optional) Executed if false.

Examples:

$collection = new Collection([1, 2, 3]);

$collection->when(true, function ($c) {
return $c->push(4);
});

Unless True​

Execute a callback if a condition is false.

Description:

The unless() method will execute the callback if the first argument is false.

Method Signature:

public function unless(mixed $value, callable $callback, mixed $default = null): mixed

Examples:

$collection = new Collection([1, 2, 3]);

$collection->unless(false, function ($c) {
return $c->push(4);
});

ORM Loading​

Load Relationships​

Eager load relationships for all models in the collection.

Description:

The load() method eagerly loads the specified relationships for every model in the collection. This is useful for "lazy eager loading" after you have already retrieved the models.

Method Signature:

public function load(mixed $relations): static

Parameters:

  • $relations - A string, array of strings, or variable arguments of relationship names.

Examples:

$orders = Order::all(); // Models loaded without relations

// Later, load the items and customers
$orders->load('items', 'customer');

// Accessing them now doesn't run extra queries
foreach ($orders as $order) {
echo $order->customer->name;
}

SQL Output:

SELECT * FROM `droip_ecommerce_order_items` WHERE `order_id` IN (1, 2, 3...)
SELECT * FROM `droip_ecommerce_customers` WHERE `id` IN (10, 11, 12...)