Laravel is a powerful PHP framework that comes with many useful features, one of which is the Collection class. The Collection class provides an easy and convenient way to work with arrays of data. It offers a wide range of methods that can be used to manipulate and transform data in many different ways. In this article, we will explore some of the most useful Laravel collection methods and explain them in detail with syntax and examples.
all()
The all() method returns all items from the collection. It is a simple method that doesn’t take any parameters. Here is the syntax for using the all() method:
$collection->all();
Here is an example of using the all() method:
$collection = collect(['apple', 'banana', 'orange']);$all_items = $collection->all();// Output: ['apple', 'banana', 'orange']
average()
The average() method returns the average value of a given key in the collection. It takes one parameter, which is the key to calculate the average. Here is the syntax for using the average() method:
$collection->average('key');
Here is an example of using the average() method:
$collection = collect([ ['name' => 'John', 'age' => 20], ['name' => 'Jane', 'age' => 25], ['name' => 'Jack', 'age' => 30]]);$average_age = $collection->average('age');// Output: 25
chunk()
chunk()
method is used to split an array or collection into smaller arrays of a specified size. The syntax for this method is as follows:
chunk($collection, $size);
Here, $collection
is the array or collection that you want to split, and $size
is the size of each chunk you want to create. For example:
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];$chunks = chunk($array, 3);
This will split the $array
into smaller arrays of size 3. The result will be:
[ [1, 2, 3], [4, 5, 6], [7, 8, 9],]
collapse()
collapse()
method is used to merge multiple arrays or collections into a single array. The syntax for this method is as follows:
collapse($collection);
Here, $collection
is the array or collection that you want to merge. For example:
$array1 = [1, 2, 3];$array2 = [4, 5, 6];$array3 = [7, 8, 9];$merged = collapse([$array1, $array2, $array3]);
This will merge the three arrays into a single array. The result will be:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
contains()
contains()
method is used to check if a value exists in a collection. The syntax for this method is as follows:
contains($collection, $value);
Here, $collection
is the array or collection that you want to search in, and $value
is the value that you want to search for. For example:
$array = [1, 2, 3, 4, 5];$contains = contains($array, 3);
This will check if the value 3 exists in the $array
. The result will be true
.
Count()
count()
method is used to get the number of items in a collection or an array. The syntax for this method is as follows:
count($collection);
Here, $collection
is the collection or array that you want to count the items in. For example:
$array = [1, 2, 3, 4, 5];$count = count($array);
This will return the number of items in the $array
, which is 5.
diff()
diff()
method is used to get the items that are not present in the given collection(s). The syntax for this method is as follows:
diff($collection1, $collection2, ...);
Here, $collection1
, $collection2
, and so on are the collections or arrays that you want to compare. For example:
$array1 = [1, 2, 3, 4, 5];$array2 = [3, 4, 5, 6, 7];$diff = diff($array1, $array2);
This will return the items that are present in $array1
but not in $array2
, which are [1, 2]
.
each()
each()
method is used to iterate over a collection and call a callback function on each item. The syntax for this method is as follows:
each($collection, $callback);
Here, $collection
is the collection or array that you want to iterate over, and $callback
is the function that you want to call on each item. For example:
$array = [1, 2, 3, 4, 5];each($array, function($item, $key) { echo "Item $key is $item\n";});
This will print out each item in the $array
with its key.
filter()
filter()
method is used to filter a collection using a given callback function. The syntax for this method is as follows:
filter($collection, $callback);
Here, $collection
is the collection or array that you want to filter, and $callback
is the function that you want to use to filter the collection. For example:
$array = [1, 2, 3, 4, 5];$filtered = filter($array, function($item) { return $item > 3;});
This will return a new array with only the items that are greater than 3, which are [4, 5]
.
first()
first()
method is used to get the first item in a collection. The syntax for this method is as follows:
first($collection);
Here, $collection
is the collection or array that you want to get the first item from. For example:
$array = [1, 2, 3, 4, 5];$first = first($array);
This will return the first item in the $array
, which is 1.
flatmap()
flatMap()
method is used to map a collection and then flatten the results by one level. The syntax for this method is as follows:
flatMap($callback);
Here, $callback
is the function that you want to apply to each item in the collection. The result of this function will be flattened into a single level array. For example:
$array = [1, 2, 3, 4, 5];$flatMapped = flatMap(function($item) { return [$item, $item * 2];});
This will map each item in the $array
to a new array with the item and its double, and then flatten the result into a single level array, which will be [1, 2, 2, 4, 3, 6, 4, 8, 5, 10]
.
flatten()
flatten()
method is used to flatten a multi-dimensional collection into a single level. The syntax for this method is as follows:
flatten($depth);
Here, $depth
is the maximum depth to which the collection should be flattened (default is 1). For example:
$array = [1, [2, [3, [4]]]];$flattened = flatten($array);
This will flatten the $array
into a single level, which will be [1, 2, [3, [4]]]
.
flip()
flip()
method is used to flip the keys and values of a collection. The syntax for this method is as follows:
flip();
For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$flipped = flip($array);
This will flip the keys and values of $array
, which will be [1 => 'a', 2 => 'b', 3 => 'c']
.
forget()
forget()
method is used to remove an item from a collection by its key. The syntax for this method is as follows:
forget($key);
Here, $key
is the key of the item that you want to remove from the collection. For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$forget = forget('b');
This will remove the item with the key 'b'
from $array
.
get()
get()
method is used to get an item from a collection by its key. The syntax for this method is as follows:
get($key, $default);
Here, $key
is the key of the item that you want to get, and $default
is the default value to return if the item is not found (optional). For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$value = get('b');
This will return the value of the item with the key 'b'
from $array
, which is 2
. If the key is not found, it will return null.
groupBy()
groupBy()
method is used to group the collection by a given key. The syntax for this method is as follows:
groupBy($key);
Here, $key
is the key by which you want to group the collection. For example:
$array = [ ['name' => 'John', 'age' => 20], ['name' => 'Jane', 'age' => 25], ['name' => 'Joe', 'age' => 20],];$grouped = groupBy('age', $array);
This will group the $array
by age, resulting in an array with two keys: 20
and 25
. Each key will contain an array of items that have that age.
has()
has()
method is used to determine if the collection has an item by its key. The syntax for this method is as follows:
has($key);
Here, $key
is the key of the item that you want to check for existence. For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$has = has('b', $array);
This will return true
because the key 'b'
exists in $array
.
implode()
implode()
method is used to concatenate values of a given key as a string. The syntax for this method is as follows:
implode($glue, $key);
Here, $glue
is the string that you want to use to separate the values, and $key
is the key of the values that you want to concatenate. For example:
$array = [ ['name' => 'John', 'age' => 20], ['name' => 'Jane', 'age' => 25], ['name' => 'Joe', 'age' => 20],];$imploded = implode(', ', 'name', $array);
This will concatenate the names of each item in $array
with a comma and a space, resulting in the string 'John, Jane, Joe'
.
intersect()
intersect()
method is used to get the items that are present in both the given collection(s). The syntax for this method is as follows:
intersect($array1, $array2, ...);
Here, $array1
, $array2
, etc. are the arrays that you want to intersect. For example:
$array1 = [1, 2, 3, 4];$array2 = [3, 4, 5, 6];$intersected = intersect($array1, $array2);
This will return the items that are present in both $array1
and $array2
, which will be [3, 4]
.
isEmpty()
isEmpty()
method is used to determine if the collection is empty. The syntax for this method is as follows:
isEmpty();
For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$empty = isEmpty($array);
This will return false
because $array
is not empty.
keyBy()
keyBy()
method is used to create a new collection keyed by a given key. The syntax for this method is as follows:
keyBy($callback);
Here, $callback
is the function that will be used to determine the key for each item in the collection. For example:
$array = [ ['id' => 'foo', 'name' => 'Foo'], ['id' => 'bar', 'name' => 'Bar'], ['id' => 'baz', 'name' => 'Baz']];$keyedBy = keyBy(function($item) { return $item['id'];});
This will create a new collection keyed by the 'id'
field of each item in the $array
.
keys()
keys()
method is used to get all of the keys from the collection. The syntax for this method is as follows:
keys();
For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];$keys = keys($array);
This will return an array containing all of the keys in $array
, which will be ['a', 'b', 'c']
.
last()
last()
method is used to get the last item in the collection. The syntax for this method is as follows:
last();
For example:
$array = [1, 2, 3, 4, 5];$last = last($array);
This will return the last item in $array
, which will be 5
.
Map():
The map() method is used to apply a callback function to each item in the collection and return a new collection with the results. The syntax for using map() is as follows:
$collection->map(function($item, $key) { // callback function logic here return $modifiedItem;});
Example:
Suppose you have a collection of products, and you want to modify the names of each product by adding a prefix “New “. You can use map() method as follows:
$products = collect([ ['name' => 'Product 1', 'price' => 100], ['name' => 'Product 2', 'price' => 200], ['name' => 'Product 3', 'price' => 300]]);$newProducts = $products->map(function($product, $key) { $product['name'] = "New " . $product['name']; return $product;});// Output: [{"name":"New Product 1","price":100},{"name":"New Product 2","price":200},{"name":"New Product 3","price":300}]
Reduce():
The reduce() method is used to apply a callback function to each item in the collection and return a single value that is the result of the function. The syntax for using reduce() is as follows:
$collection->reduce(function($carry, $item) { // callback function logic here return $result;});
Example:
Suppose you have a collection of numbers, and you want to get the sum of all the numbers. You can use the reduce() method as follows:
$numbers = collect([1, 2, 3, 4, 5]);$total = $numbers->reduce(function($carry, $number) { return $carry + $number;});// Output: 15
Slice():
The slice() method is used to return a new collection with a slice of the items starting at a specified index and with a specified length. The syntax for using slice() is as follows:
$collection->slice($start, $length);
Example:
Suppose you have a collection of products, and you want to get a slice of the first two products. You can use the slice() method as follows:
$products = collect([ ['name' => 'Product 1', 'price' => 100], ['name' => 'Product 2', 'price' => 200], ['name' => 'Product 3', 'price' => 300]]);$sliceProducts = $products->slice(0, 2);// Output: [{"name":"Product 1","price":100},{"name":"Product 2","price":200}]
Shuffle():
The shuffle() method is used to return a new collection with the items randomly shuffled. The syntax for using shuffle() is as follows:
$collection->shuffle();
Example:
Suppose you have a collection of numbers, and you want to shuffle the order of the numbers. You can use the shuffle() method as follows:
$numbers = collect([1, 2, 3, 4, 5]);$shuffledNumbers = $numbers->shuffle();// Output: [5, 3, 1, 4, 2]
Sort():
The sort() method is used to return a new collection with the items sorted by a specified key
or using a custom comparison function. The syntax for using sort() is as follows:
$collection->sort($callback);
Example:
Suppose you have a collection of products, and you want to sort them by price in ascending order. You can use the sort() method as follows:
$products = collect([ ['name' => 'Product 1', 'price' => 100], ['name' => 'Product 2', 'price' => 200], ['name' => 'Product 3', 'price' => 300]]);$sortedProducts = $products->sort(function($a, $b) { return $a['price'] - $b['price'];});// Output: [{"name":"Product 1","price":100},{"name":"Product 2","price":200},{"name":"Product 3","price":300}]
Pluck():
The pluck() method is used to return a new collection with the values of a specified key from each item in the collection. The syntax for using pluck() is as follows:
$collection->pluck($key);
Example:
Suppose you have a collection of products, and you want to get an array of all the product names. You can use the pluck() method as follows:
$products = collect([ ['name' => 'Product 1', 'price' => 100], ['name' => 'Product 2', 'price' => 200], ['name' => 'Product 3', 'price' => 300]]);$productNames = $products->pluck('name')->toArray();// Output: ["Product 1", "Product 2", "Product 3"]
Unique():
The unique() method is used to return a new collection with only the unique items in the collection. The syntax for using unique() is as follows:
$collection->unique();
Example:
Suppose you have a collection of numbers with duplicates, and you want to get a new collection with only the unique numbers. You can use the unique() method as follows:
$numbers = collect([1, 2, 3, 2, 4, 3, 5]);$uniqueNumbers = $numbers->unique();// Output: [1, 2, 3, 4, 5]
These are just a few examples of the many useful collection methods available in Laravel. By using these methods, you can manipulate and transform your data in a variety of ways to make your code more concise and efficient.
Conclusion:
In this article, we have explored some of the most useful collection methods available in Laravel. These methods allow you to manipulate and transform your data in a variety of ways, making your code more efficient and concise. By using these methods, you can avoid writing complex loops and conditionals, which can save you time and effort. Whether you’re working with arrays, objects, or database results, Laravel’s collection methods can help you get the most out of your data.
Comments
Post a Comment