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.