collect()

collect() creates a Collection from an array or other value.

Syntaxcollect($array);

The collect() helper is the quickest way to create a Collection. Pass it an array (or anything iterable) and you immediately get access to every collection method.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A controller wraps raw JSON decoded from a webhook body with collect() to immediately use filter() and map() without touching the plain PHP array functions.
  • A seeder uses collect() to wrap a hardcoded array of fixture data, then calls each() to insert each record into the database.
  • A service method receives a mixed array-or-collection argument and wraps it with collect() at entry to ensure all downstream code works with a unified API.

More examples

Wrap an array with collect()

collect() converts a plain PHP array into a Collection instance, enabling fluent chaining of unique(), sort(), and values().

Example · php
$raw = [3, 1, 4, 1, 5, 9, 2, 6];

$result = collect($raw)
    ->unique()
    ->sort()
    ->values();
// => Collection [1, 2, 3, 4, 5, 6, 9]

Collect JSON from a webhook

Wraps the incoming webhook events array with collect(), filters to payment events, plucks order IDs, and passes them to a bulk update.

Example · php
public function handleWebhook(Request $request): JsonResponse
{
    $events = collect($request->input('events', []))
        ->filter(fn($e) => $e['type'] === 'payment.succeeded')
        ->pluck('data.order_id');

    Order::whereIn('id', $events)->update(['paid' => true]);

    return response()->json(['processed' => $events->count()]);
}

Normalise mixed input in a service

Calling collect() on a value that is already a Collection is safe and returns it unchanged, making this pattern a reliable normaliser.

Example · php
use Illuminate\Support\Collection;

public function process(array|Collection $items): void
{
    $collection = collect($items); // safe whether array or Collection

    $collection->each(fn($item) => $this->handleItem($item));
}

Discussion

  • Be the first to comment on this lesson.