Understanding Laravel Collection Methods with Example

Understanding Laravel Collections Methods with Example

What is Laravel Collection?

While developing the web application using Laravel Framework, Have you ever observed what happens when you make Laravel Model (Laravel Eloquent) queries to retrieve database results? Meaning that in which format Laravel framework returns the result set. Yes, its Laravel Collection to collect the data into key-value pair structured form.

The collection is just a wrapper around arrays which provides a set of methods to manipulate the data.

Whenever you make Laravel Eloquent query to retrieve database results, Laravel returns data in form of multiple rows, instead of an array they’ll come packaged in a Laravel collection. Laravel Collection is also known as Eloquent collection which is a specialized type of collection. Laravel’s Eloquent ORM also returns data in the form of collectins.

 

Read our detailed chapter Laravel Request Lifecycle, How Laravel request is received and served?

For example – here $posts is a collection which is an array of objects with additional attributes:

$posts = TechCluesBlogPosts::all ();

The collection data would look like this:
[
['title' => 'Wordpress Plugins', 'views' => 10],
['title' => 'Laravel Collections', 'views' => 500],
['title' => 'Android Development', 'views' => 1000],
['title' => 'The Miracle Morning', 'views' => 500],
]

In this tutorial, we will also demonstrate the use of various Laravel Collection methods.

If you are a beginner to Laravel MVC, then we recommend to study the following topics:

 

Why use Laravel Eloquent Collections?

Laravel collection is one of the most powerful features of the Laravel framework to manipulate user data.

It allows developers to query the database only once, and then perform all the operations (get the first record, last record, count, compare, etc). Laravel developers need not query the database for each action to be performed on the result set. Collections help developers to avoid database connection overheads by working offline with data.

Laravel Collection vs PHP Arrays?

Collections in Laravel are somewhat similar to PHP Arrays, but are more powerful and provide developers level of flexibility to manipulate data. Let’s take a look at collections and Eloquent collections, and understand what makes Laravel Collections much better than plain PHP arrays. Laravel Collections is a collection of array objects with some additional features to better manipulate the data retrieved from the database queries.

How Collections can be used in Laravel?

Laravel Eloquent models return results as collections. But, the concept of collections can also be used separately while laravel web app development. Laravel collections provide developers very convenient methods to modify, filter results and even more operations.

You can simply create a collection by passing an array to collect() helper function. All of the next collection methods listed below are applicable to both the eloquent collections and collections itself as well.

How to create a new collection in Laravel?

As we have learned that we can create our custom collections and perform various operation on them like – modify, filer, count, etc. The new collection can simply be created using the collect() method like this:

$students = collect([
    [
        'student_id' => '1',
        'name' => 'Student1',
        'class' => 'Class1',
        'stream' => 'Physics'
    ],
    [
        'student_id' => '2',
        'name' => 'Student2',
        'class' => 'Class2',
        'stream' => 'Chemistry'
    ],
    [
        'student_id' => '3',
        'name' => 'Student3',
        'class' => 'Class3',
        'stream' => 'Maths'
    ],
]);

All the laravel collection methods used on Eloquent are used with a custom user-defined collection in laravel as well.

Let’s understand in detail what all operations can be performed on collections and learn the related methods.

List of Laravel Collection Methods

The most common use cases of using the Laravel collections is to avoid frequent calls to query the database. Once all the database results are retrieved as a collection, they can be manipulated as per developer needs i.e – modify the results, delete, split, filter, sort, count, and even much more.

Let’s go through all the available laravel collection methods:

all() – Get all the results

The new collection can simply be created using the collect() method like this:

$websites = collect([
        'www.website1.com',
        'www.website2.com',
        'www.website3.com',
        'www.website4.com',
        'www.website5.com',
        'www.website6.com'
    ]);
 
  $all = $websites->all();

Result
/*
array:6 [▼
0 => "www.website1.com"
1 => "www.website2.com"
2 => "www.website3.com"
3 => "www.website4.com"
4 => "www.website5.com"
5 => "www.website6.com"
]
*/

Laravel Collection avg() Method

Returns the average value of given keys.

$average = collect([100, 100, 200, 400])->avg();

Result - 200

Laravel Collection chunk() Method

The chunk() method is used to split the collection into smaller collections of the same given size.

$collection = collect([10, 20, 30, 40, 50, 60, 70]);

$chunks = $collection->chunk(4);

$chunks->toArray();

Result - [[1, 2, 3, 4], [5, 6, 7]]

concat() – Concatenate collections in Laravel

The concat() method is used to concatenate the given array. This appends at the end of the collection.

$collection = collect(['TechCluesBlog Tutorials']);

$concatenated = $collection->concat(['Laravel'])->concat(['name' => 'WordPress']);

$concatenated->all();

Result - ['TechCluesBlog Tutorials', 'Laravel', 'WordPress']

count() – counts the number of collections in Larvel

The count() method returns the total number of items contained in the laravel collection.

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

$collection->count();

Result - 4

Laravel collection dd() vs dump() methods

The dd() method performs 2 operations – dumps the collection items and stop the script execution.

$collection = collect(['TechCluesBlog', 'Tutorials']);

$collection->dd();

Output:
/*
    Collection {
        #items: array:2 [
            0 => "TechCluesBlog"
            1 => "Tutorials"
        ]
    }
*/

The dump method dumps the collection’s items without stopping the script execution.

Filter the Laravel collection

filer() is Laravel’s most useful collection method() which allows the developers to filer out the collection with a callback. The items which are passed in the callback are kept, other items are removed from the collection.

$collection = collect([11, 12, 13, 14]);

$filteredResult = $collection->filter(function ($value, $key) {
    return $value > 12;
});

$filteredResult ->all();

Result - [13, 14]

first() – get first item of collection

The first() method returns the first item of the collection. It can be used with arguments to check conditions or without arguments.

$first_item = collect([1, 2, 3, 4])->first();

Result - 1

Whenever the first() method is called on Eloquent collection, in that case, it returns the first record of Model.

get() – Get given key in Laravel

The get() method is used to retrieve the item with a given key name.

$collection = collect(['name' => 'Taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

Result - Taylor

isEmpty() – Check if Laravel collection is empty?

the isEmpty() collection method checks if the given collection is empty or not. Returns true if the collection is empty,
otherwise false if it contains some data.

collect([])->isEmpty();

Result - // true

Get the minimum value of the collection in Laravel

$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
Result - 10 Result - 10

$min = collect([1, 2, 3, 4, 5])->min();

Result - 1
Whenever the last() method is called on Eloquent collection, in that case it returns the first record of Model.

shuffle() – Shuffle the elements of Laravel collection

The shuffle() is used to shuffle the elements of a given collection randomly.

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

$shuffled = $collection->shuffle();
$shuffled->all();

Result - [3, 2, 5, 1, 4] - (generated randomly)

slice() – slice the collection

The slice() method is used to slice the collection with the given index.

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$slice = $collection->slice(4);

$slice->all();

Result - [5, 6, 7, 8, 9, 10]

sort() – sort items in Laravel collection

The sort() is the most powerful and useful method to sort the elements in Laravel collection.

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

$sorted = $collection->sort();

$sorted->values()->all();

Result - [1, 2, 3, 4, 5]

split() – split the collection into groups

The split method is used to split the laravel collection into a given number of equal groups.

$collection = collect([1, 2, 3, 4, 5]);
$groups = $collection->split(3);

$groups->toArray();

Result - [[1, 2], [3, 4], [5]]

unique() – Get the Unique items from Laravel collection

The unique() can be used to get the list of unique items from the given collection.

$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();

$unique->values()->all();

Result - [1, 2, 3, 4]

Laravel Collection where() method

The where() method is used to get the items from a collection with a given key-value pair.

$collection = collect([
    ['Book' => 'Laravel', 'price' => 500],
    ['Book' => 'WordPress', 'price' => 450],
    ['Book' => 'C++', 'price' => 850],
    ['Book' => 'Java', 'price' => 450],
]);

$filtered = $collection->where('price', 450);

$filtered->all();

Result
[
   ['Book' => 'WordPress', 'price' => 450],
   ['Book' => 'Java', 'price' => 450],
]

Laravel Collection whereBetween()

The whereBetween() method in Laravel collection returns the list of items falling between the given range of values:

$collection = collect([
     ['Book' => 'Laravel', 'price' => 500],
     ['Book' => 'WordPress', 'price' => 450],
     ['Book' => 'C++', 'price' => 850]
]);

$filtered = $collection->whereBetween('price', [400, 500]);

$filtered->all();

Result
[
   ['Book' => 'Laravel', 'price' => 500],
   ['Book' => 'WordPress', 'price' => 450]
]

except() method in Laravel Collection

Suppose you need to get the list of items from collection excluding few keys, then use the except() method.

$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);
$filtered = $collection->except(['price', 'discount']);

$filtered->all();

Result - ['product_id' => 1]

Conclusion

Important to note that all the operations performed on Laravel collections does not make any database query or perform DB action. All the collection methods() mentioned above are operated on the returned result set of collections.

Further Reading:

Laravel Official documentation
Laravel Collection Tutorial

Laravel Scotch Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *