Laravel Tutorials

Convert Any Value to Collections with Laravel's Collection::wrap Method

Published
Convert Any Value to Collections with Laravel's Collection::wrap Method image

Laravel's Collection::wrap method provides seamless conversion of various data types into collections, ensuring consistent collection handling regardless of input format.

The wrap method handles different value types gracefully:

use Illuminate\Support\Collection;

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

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

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

Here's how you might use it in an email notification service:

class NotificationService
{
    public function sendEmails($recipients, $message)
    {
        return Collection::wrap($recipients)
            ->map(fn($email) => $this->validateEmail($email))
            ->filter()
            ->each(fn($email) => $this->dispatch($email, $message));
    }
    
    public function assignCategories($product, $categories)
    {
        $currentCategories = $product->categories;
        $newCategories = Collection::wrap($categories)
            ->unique()
            ->diff($currentCategories);
            
        $product->categories()->sync($newCategories);
        
        return $product;
    }

    public function formatNotifications($notifications)
    {
        return Collection::wrap($notifications)
            ->map(fn($notification) => [
                'id' => $notification->id,
                'message' => $notification->content,
                'timestamp' => $notification->created_at
            ])
            ->sortByDesc('timestamp');
    }
}

class AlertController extends Controller
{
    public function broadcast(Request $request, NotificationService $service)
    {
        $alerts = AlertService::latest($request->limit);
        return $service->formatNotifications($alerts);
    }
}

The wrap method ensures consistent collection handling regardless of input type, making your code more reliable and flexible.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article