lists($value, $key = null)
The lists
method is an alias of the pluck
method. The lists
method is used to retrieve the a list of values from the collection. It defines two parameters: $value
and $key
. The $value
indicates which property should become the value in the resulting collection and the $key
parameter indicates which property should become the key in the resulting collection.
The following code example will demonstrate the usage of the lists
method to retrieve a collection of the product names and versions:
1<?php
2
3use Illuminate\Support\Collection;
4
5// Create a new collection.
6$collection = new Collection([
7 ['name' => 'Laravel', 'version' => '5.1'],
8 ['name' => 'Lumen', 'version' => '5.0']
9]);
10
11// Get a list of product names.
12$productNames = $collection->lists('name');
13
14// Get a list of product versions.
15$productVersions = $collection->lists('version');
After the above code has been executed, the $productNames
variable would contain a value similar to the following output:
1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string 'Laravel' (length=7)
5 1 => string 'Lumen' (length=5)
and the $productVersions
variable would contains a value similar to the following output:
1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 0 => string '5.1' (length=3)
5 1 => string '5.0' (length=3)
The following code example will return a new collection with the version as the value and the product name as the key of the resulting collection:
1<?php
2
3$products = $collection->lists('version', 'name');
The $products
variable would then contain a value similar to the following output:
1object(Illuminate\Support\Collection)[134]
2 protected 'items' =>
3 array (size=2)
4 'Laravel' => string '5.1' (length=3)
5 'Lumen' => string '5.0' (length=3)
∎