Learn and use Collections in Laravel

Tram Ho

People often say that laravel framework is very powerful so where is it powerful? For me, any Laravel component is powerful. In this article, we will learn about a very important component in laravel, Collection.

What is Laravel Collection?

Laravel Collection is a class that provides methods that focus on handling arrays of data in a convenient way to minimize the time for programmers. Especially as an API to connect to the database because the data returned from the database is of type Collection. collection example:

Using Laravel Collection

Collection initialization

Initialize the collection by simply doing the following

Initialization via helper collect

$collection = collect([1, 2, 3]);

Initialization via Collection class

$collection = new \Collection([1, 2, 3, 4, 5]);

Doesn’t it look like an array?

Commonly used Collections.

Laravel collection has a lot of methods that make it easier for developers to process data.

all()

This method retrieves data from the collection and returns array data

$data = Collection::make([1, 2, 3, 4, 5, 6])->all();

//output [1,2,3,4,5,6];

get

The function gets the value of the element in the array.

first()

The first() method returns the first element in the collection

pluck()

The pluck() method will return the entire value of a key of each element in the collection

SortBy The function rearranges in ascending order.

Take The function limits the number of returns.

count The function counts the elements in collections.

avg The function calculates the average value of the elements in the array.

push()

The push() method will add a new element to the end of the collection

values()

The values() function returns the value of a new collection and generates the keys to consecutive integers

chumk Functions that split an array into sub-arrays.

Share the news now