November 30, 2016 —John Koster
except($keys)
The except
method will return all the key/value pairs in the collection where the keys in the collection are not in the supplied $keys
array. Internally, this method makes a call to the Illuminate\Support\Arr:except($array, $keys)
helper function.
The following example demonstrates the usage of the except
method:
1<?php 2 3// Create a new collection. 4$collection = collect([ 5 'first_name' => 'John', 6 'last_name' => 'Doe', 7 'password' => 'some_password' 8]); 9 10// Retrieve all items from the collect11// except for the password.12$data = $collection->except(['password']);
After the above code has executed, the $data
variable would contain a value similar to the following output:
1Collection {2 #items: array:2 [3 "first_name" => "John"4 "last_name" => "Doe"5 ]6}
We can also combine the except
method with the toJson
method to easily remove sensitive data from information before sending it to an end user:
1<?php2 3$jsonData = $collection->except(['password'])->toJson();
After the above code has executed, the $jsonData
variable would hold a value similar to the following JSON string:
1"{"first_name":"John","last_name":"Doe"}"
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.