Skip to content
Using Laravel's Collection::wrap to Convert Any Value into a Collection

Using Laravel's Collection::wrap to Convert Any Value into a Collection

The article explains Laravel's Collection::wrap method, showing basic usage for wrapping scalars, arrays, or existing collections, and provides real-world examples within a data‑processing service to streamline handling of items, tags, and search results.

php Courses
php Courses
php Courses

Laravel provides the Collection::wrap method, which can effortlessly convert any value—whether a scalar, array, or object—into a collection, ensuring consistent collection handling throughout your code.

Basic Usage

Wrap different types of values into a collection:

use Illuminate\Support\Collection;

// Wrap a single value
$collection = Collection::wrap('John Doe');
// Result: ['John Doe']

// Wrap an array
$collection = Collection::wrap(['John Doe']);
// Result: ['John Doe']

// Wrap an existing collection
$collection = Collection::wrap(collect('John Doe'));
// Result: ['John Doe']

Real‑World Example

Below is a typical usage within a data‑processing service:

class DataProcessor
{
    public function processItems($items)
    {
        return Collection::wrap($items)
            ->map(fn($item) => $this->formatItem($item))
            ->filter()
            ->values();
    }

    public function addTags($entity, $tags)
    {
        $existingTags = $entity->tags;
        $newTags = Collection::wrap($tags)
            ->unique()
            ->diff($existingTags);

        $entity->tags()->attach($newTags);
        return $entity;
    }

    public function processSearchResults($results)
    {
        return Collection::wrap($results)
            ->map(fn($result) => [
                'id'    => $result->id,
                'title' => $result->title,
                'url'   => $result->url,
            ])
            ->sortBy('title');
    }
}

// Usage in a controller
class SearchController extends Controller
{
    public function search(Request $request, DataProcessor $processor)
    {
        $results = SearchService::find($request->query);
        return $processor->processSearchResults($results);
    }
}

The wrap method unifies various input types into a collection, improving code reliability, flexibility, and simplifying subsequent collection operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPLaravelDataProcessingcollection
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.