Laravel Collection Public API: only

November 30, 2016 —John Koster

only($keys)

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. Internally, this method makes a call to the Illuminate\Support\Arr::only($array, $keys) helper function.

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<?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 only the first and last
11// names from the collection.
12$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:2 [
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.