Removing Collection Items with Laravel's forget Method
Need to remove items from a collection? Laravel's forget method offers a straightforward way to remove elements by their keys while modifying the original collection.
Basic Usage
Remove items by their keys:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
// Remove a single key
$collection->forget('name');
// Result: ['framework' => 'laravel']
// Remove multiple keys
$collection->forget(['name', 'framework']);
// Result: []
Real-World Example
Here's how you might use it in a user preferences manager:
class PreferencesManager
{
protected $preferences;
public function __construct(array $preferences)
{
$this->preferences = collect($preferences);
}
public function resetToDefault(string|array $keys)
{
// Directly modifies the preferences collection
$this->preferences->forget($keys);
return $this;
}
public function cleanupTemporarySettings()
{
$temporaryKeys = ['temp_theme', 'session_view', 'cache_key'];
$this->preferences->forget($temporaryKeys);
return $this;
}
public function removeOutdatedFlags(array $flags)
{
// Remove specific feature flags
$this->preferences
->forget(
collect($flags)
->map(fn($flag) => "feature_flag.{$flag}")
->all()
);
return $this;
}
}
// Usage
$manager = new PreferencesManager([
'theme' => 'dark',
'notifications' => true,
'temp_theme' => 'light',
'feature_flag.beta' => true
]);
$manager->cleanupTemporarySettings()
->removeOutdatedFlags(['beta']);
Unlike other collection methods, forget modifies the original collection, making it perfect for direct data manipulation.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!