Collections in Laravel 9

Tram Ho

In today’s Laravel Certification exam review series, I would like to introduce collections, the purpose of which is to note down the knowledge for myself and you to follow the article with a “detailed” document.

Start!

I. Collections Overview

Collection in Laravel is a powerful and flexible data structure that allows you to work with a collection of elements in various forms. Collection provides you with methods to filter, sort, transform, and manipulate the data in that collection.

Collection is designed to work efficiently with PHP databases and functions. It can be used to process data returned from database queries, or to filter, sort, and display complex collections.

Some of the Collection features in Laravel include:

  • Methods to filter and sort the elements in the collection based on different conditions.
  • Methods to transform data in a collection by adding or removing elements.
  • Methods to perform operations like map, reduce, and filter on the collection.
  • The ability to combine collections together to create new collections.
  • Methods to handle collection elements in a flexible way.
  • Ability to use collections with Eloquent to query and sort data in the database.

With Collection, you can perform complex operations on a collection of elements easily and efficiently, saving you time and increasing the performance of your Laravel application.

II. Collections functions in Laravel 9

In summary, there are nearly 70 collections functions in Laravel and I would like to explain each function in detail. This post can be quite long, but it contains a lot of information

I will apply this collect pattern, please remember to the end of the article.

1. Add elements in collections

Add an element to the collection:

  1. push($value) : Add an element to the end of the collection (1 element or an array of elements).

image.png and

image.png

  1. put($key, $value) : Add or update an element or an array with the corresponding key in the collection. If $key already exists, put will overwrite the new value ; otherwise, it will add the corresponding key and value .Example: dd($countries->put(2, "American"))

image.png

image.png

  1. prepend($value) : Add an element to the beginning of the collection.Example: dd($countries->prepend(2, "American"))

image.png

2. Delete an element in the collection

  1. forget($key) : Remove the element with the corresponding key from the collection, if the key is not there, nothing will happen.Example: dd($countries->forget(1))

    image.png

  2. pull($key, $default = null) : Removes the element with the corresponding key from the collection and returns the value of that element, if the key does not exist, returns null . Suppose we set the variable $default = "ahihihi" then display ahihihi instead of null
  3. pop() : Removes the last element from the collection and returns its value.
  4. reject($callback) : Removes all elements in the collection that do not satisfy the callback function’s condition. (This is also a method to filter elements that do not satisfy the condition of the callback function in the collection, but if someone asks you to list some methods to delete, this method also satisfies the condition, obviously it deletes that)For example:

image.png

3. Editing an element in a collection

  1. transform($key) : Apply a callback function to each element of the collection and overwrite the old values ​​with the new values.

For example

image.png

  1. map($callback) : Creates a new collection by applying a callback function to each element of the collection.

image.png

  1. merge($items) : Creates a new collection by combining the current collection with another collection or an array.

For example we have the following:

image.png

  1. replace($items) : Creates a new collection by replacing all elements in the collection with other elements provided in a new array or collection.

image.png

4. Sort the elements in the collection

  1. sort() : Sorts a Collection in ascending order of the element’s value.

  1. sortBy($key) : Sorts a Collection using a key .

  1. sortByDesc($key) : Sorts a Collection in descending order using a key .

  1. sortKeys() : Sorts a Collection in ascending order of the key of the elements.

Result:

  1. sortKeysDesc() : Sorts a Collection in descending order of the key of the elements.

Result:

5. Filter elements in the collection

  1. filter($callback) : Filters the elements of the collection based on the condition specified in $callback and returns a new collection containing the filtered elements.

  1. reject($callback) : Similar to the filter() method, but returns the elements that do not satisfy the condition.

  1. where($key, $operator, $value = null) : Filters the elements of the collection based on the value of an attribute. $key is the property name, $operator is the comparison operator (eg =, >, <…), and $value is the value to compare. If there are only 2 parameters in function where => default operator is “=”

Result:

  1. whereStrict($key, $value) : Similar to the where() method, but compares the value of the attribute and $value by the exact comparison type (including data type). For example

Result:

  1. whereIn($key, $values) : Filters elements with a value of the $key attribute in an array of $values.

Result:

  1. whereInStrict($key, $values) : Similar to whereIn but will set additional data types. For example:

  1. whereNotIn($key, $values) : Similar to whereIn() method, but filters elements that are not in the $values ​​array.

Result:

  1. whereNotInStrict($key, $values) : Similar to the whereNotIn() method, but filters elements that are not in the $values ​​array.

Result:

  1. whereBetween($key, $values) : Filters elements where the value of the $key attribute ranges from $values[0] to $values[1].

For example :

Result:

  1. whereNull($key) : Filters elements where the value of $key attribute is null .

Result:

  1. whereNotNull($key) : Filters elements whose value of the $key attribute is null .

Result:

5. Collections support handling strings, arrays

  1. join($glue, $finalGlue = null) : used to combine the elements of a collection into a single string, with the elements separated by a specified string.

In there :

  • $glue : is the string that separates the elements.
  • $finalGlue : is the string separating the last element and the preceding element. If you don’t want a string separator on the last element, the value of $finalGlue will be null.

For example:

  1. crossJoin(…$collections) : is a Collection method in Laravel, it is used to calculate all combinations of values ​​in the provided collections.

For example :

Result:

  1. mapInto(string $class) : Apply a function to each element in the collection and return a new collection. In this case, we can use the map method to process the strings in the collection.

  1. mapSpread($callback) : is a collection method in Laravel, used to transform elements in the Collection using a callback function, but with a different behavior than the map() and mapWithKeys() .

The difference of mapSpread() from map() and mapWithKeys() methods is the parameter passed to the callback function. Instead of passing a single value for each element in the Collection, mapSpread() will pass in multiple arguments corresponding to the values ​​of each element in the Collection.

For example:

  1. mapToGroups($callback) in Laravel Collection is used to transform a Collection into an array grouped by a specific property.

For example:

Result:

  1. mapWithKeys($callback) : in Laravel Collection allows to transform Collection values ​​into a new key-value associative array. It uses a callback function to do this and returns a new Collection with the key-value pairs generated by the callback function.

For example :

Result:

Share the news now

Source : Viblo