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

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

Laravel 5

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

public function only(
    $keys
);

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:

// Create a new collection.
$collection = collect([
    'first_name' => 'John',
    'last_name'  => 'Doe',
    'password'   => 'some_password'
]);

// Retrieve only the first and last
// names from the collection.
$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:

Collection {
  #items: array: [
    "first_name" => "John"
    "last_name"  => "Doe"
  ]
}

Start the Discussion

Leave a comment

Subscribe to our newsletter