Search

Laravel 5 Collections: Retrieving a Subset Of a Collections Elements With only

April 22, 2018 —John Koster

The only method is the logical opposite of the except method. The only method is used to return all the key/value pairs in the collection where the keys in the collection are in the supplied $keys array.

If the argument supplied for $keys evaluates to null, a copy of the original collection is returned.

#Signature

1public function only(
2 $keys
3);

#Example Use

Using the same example from the except method section, we can get only the first_name and last_name of the users in a collection:

1// Create a new collection.
2$collection = collect([
3 'first_name' => 'John',
4 'last_name' => 'Doe',
5 'password' => 'some_password'
6]);
7 
8// Retrieve only the first and last
9// names from the collection.
10$data = $collection->only(['first_name', 'last_name']);

After the above code has executed, the $data variable would contain a value similar to the following output:

1Collection {
2 #items: array: [
3 "first_name" => "John"
4 "last_name" => "Doe"
5 ]
6}

Some absolutely amazing
people

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.