Laravel Collections: extract specified set of keys and set the non-existing keys to a default value

Viewed 283

I am currently using the only method to extract a certain set of keys from a Collection. This method extracts the specified keys from the Collection and doesn't extract a key if it does not exist. I am wondering if there is also a way to extract non-existing keys from a Collection and have a default value for the non-existing keys in the result.

This is the current behaviour of the only method:

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name', 'quantity']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

The behaviour I am looking for is:

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name', 'quantity']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk', 'quantity'=>'']

Is there a way of doing this? Preferably using one of the Collection's methods.

1 Answers

This can be done like this.

// The main collection to filter from
$main = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);


// From the filters array, create an empty collection with the default values
$toFilter = collect([
  'product_id' => '', 
  'name' => '', 
  'quantity' => '',
]);

// Set the the values from the main collection, 
$filteredResult = $toFilter->map(function($item, $key) use($main){

    return $main[$key] ?? $item ;

});

You should get the final collection as expected

$filteredResult->all()
[
   "product_id" => 1,
   "name"       => "Desk",
   "quantity"   => "",
]
Related