Laravel Tutorials

Remove Collection Items Directly with Laravel's forget Method

Published
Remove Collection Items Directly with Laravel's forget Method image

Laravel's collection forget method provides a straightforward approach to remove elements by their keys while modifying the original collection in place.

The forget method removes items by their keys:

$collection = collect(['email' => 'user@example.com', 'role' => 'admin']);

// Remove a single key
$collection->forget('email');
// Result: ['role' => 'admin']

// Remove multiple keys
$collection->forget(['email', 'role']);
// Result: []

Here's how you might use it in a shopping cart manager:

class CartManager
{
    protected $items;

    public function __construct(array $cartItems)
    {
        $this->items = collect($cartItems);
    }

    public function removeItems(string|array $productIds)
    {
        $this->items->forget($productIds);
        
        return $this;
    }

    public function clearExpiredDiscounts()
    {
        $expiredCoupons = ['summer_sale', 'flash_deal', 'early_bird'];
        
        $this->items->forget($expiredCoupons);
        
        return $this;
    }

    public function removeUnavailableProducts(array $outOfStock)
    {
        // Remove specific out-of-stock items
        $this->items
            ->forget(
                collect($outOfStock)
                    ->map(fn($sku) => "product_{$sku}")
                    ->all()
            );
            
        return $this;
    }
}

$cart = new CartManager([
    'product_123' => ['qty' => 2, 'price' => 29.99],
    'shipping' => 9.99,
    'summer_sale' => -5.00,
    'product_456' => ['qty' => 1, 'price' => 15.50]
]);

$cart->clearExpiredDiscounts()
     ->removeUnavailableProducts(['456']);

Unlike other collection methods, forget modifies the original collection, making it perfect for direct data manipulation.

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