Skip to content

Conversation

@techmahedy
Copy link
Member

diff() example

Get items that exist in the first collection but not in the second

// Find users who haven't made purchases
$allUsers = User::all();
$purchasers = Order::all()->pluck('user_id')->unique();
$nonPurchasers = $allUsers->pluck('id')->diff($purchasers);

// Find removed features
$oldFeatures = new Collection(Model::class, ['feature1', 'feature2', 'feature3']);
$newFeatures = new Collection(Model::class, ['feature2', 'feature4']);
$removedFeatures = $oldFeatures->diff($newFeatures); // ['feature1', 'feature3']

intersect() example

Get items that exist in both collections

// Find users in both groups
$premiumUsers = User::where('premium', true)->get()->pluck('id');
$activeUsers = User::where('last_login > ?', $date)->get()->pluck('id');
$premiumActiveUsers = $premiumUsers->intersect($activeUsers);

// Find common interests
$user1Interests = new Collection(Model::class, ['sports', 'music', 'art']);
$user2Interests = new Collection(Model::class, ['music', 'coding', 'art']);
$commonInterests = $user1Interests->intersect($user2Interests); // ['music', 'art']

tap() example

Execute a callback without modifying the collection

// Debug pipeline
$result = $users
    ->filter(fn($u) => $u['active'])
    ->tap(fn($col) => Log::info("Active users: " . $col->count()))
    ->map(fn($u) => $u['email'])
    ->tap(fn($col) => Cache::set('active_emails', $col->all()))
    ->all();

// Send notification without breaking the chain
$orders = Order::pending()
    ->tap(fn($orders) => "Send notification")
    ->update(['status' => 'processing']);

@techmahedy techmahedy merged commit 57a8a18 into doppar:3.x Jan 22, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant