Laravel
February 18
Удаление элементов коллекции методом `forget`
Необходимо удалить элементы из коллекции? Метод forget в Laravel предлагает простой способ удаления элементов по их ключам, не изменяя исходную коллекцию.
Базовое использование
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);
// Удаление отдельного ключа
$collection->forget('name');
// Result: ['framework' => 'laravel']
// Удаление нескольких ключей
$collection->forget(['name', 'framework']);
// Result: []Реальный пример
Рассмотрим как это можно использовать в менеджере пользовательских предпочтений:
class PreferencesManager
{
protected $preferences;
public function __construct(array $preferences)
{
$this->preferences = collect($preferences);
}
public function resetToDefault(string|array $keys)
{
// Прямое изменение коллекции предпочтений
$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)
{
// Удаление определенных feature flag
$this->preferences
->forget(
collect($flags)
->map(fn($flag) => "feature_flag.{$flag}")
->all()
);
return $this;
}
}
// Использование
$manager = new PreferencesManager([
'theme' => 'dark',
'notifications' => true,
'temp_theme' => 'light',
'feature_flag.beta' => true
]);
$manager->cleanupTemporarySettings()
->removeOutdatedFlags(['beta']);В отличие от других методов коллекции, forget изменяет исходную коллекцию, что делает его идеальным для прямого манипулирования данными.