Remove Nested Values in Laravel with data_forget Function
Need to remove values from deeply nested arrays? Laravel's data_forget function brings a convenient way to handle nested data removal using simple dot notation.
Basic Usage
Remove a single nested value:
$data = ['products' => ['desk' => ['price' => 100]]];
data_forget($data, 'products.desk.price');
// Result: ['products' => ['desk' => []]]
Using Wildcards
Handle multiple items with asterisk notation:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];
data_forget($data, 'products.*.price');
// Result: ['products' => [['name' => 'Desk 1'], ['name' => 'Desk 2']]]
Real-World Example
Here's how you might use it in a data cleaning service:
class DataSanitizer
{
public function cleanUserData(array $userData)
{
// Remove sensitive information
data_forget($userData, 'payment.*.card_number');
data_forget($userData, 'payment.*.cvv');
// Remove temporary processing data
data_forget($userData, 'orders.*.processing_metadata');
// Clear cached calculations
data_forget($userData, 'statistics.*.calculated_values');
return $userData;
}
public function prepareApiResponse(array $data)
{
// Remove internal fields
data_forget($data, 'items.*.internal_id');
data_forget($data, 'items.*.stock_location');
// Remove null values
foreach ($data['items'] ?? [] as $key => $item) {
if (isset($item['variants'])) {
data_forget($data, "items.{$key}.variants.*.null_fields");
}
}
return $data;
}
}
The data_forget function simplifies the process of removing specific data from complex nested structures.
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!