You are currently viewing Laravel Collections Explained

Laravel Collections Explained

Laravel Collections Explained

Hello folks, in this article, we will try to learn Laravel Collections and many other things related to Laravel Collections. Lets jump into it.

Laravel Collections Example

What is Laravel Collections?

In simpler terms, Laravel Collections provide a simpler way to work with Array data. Basically it is a wrapper over a simple PHP array. Core class definition is in “Illuminate\Support\Collection“.

Let see an example first:

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Collection;

Route::get('collections', function() {
    $collection = collect(['John', 'Jane', 'Joe', null])->map(function ($name) {
    return strtoupper($name);
  })->reject(function ($name) {
    return empty($name);
  });
    return $collection;
});

?>

Here, you can see that, we have imported Collection Class from “Illuminate\Support\Collection“. Here we are working based on an simple array:

['John', 'Jane', 'Joe', null].

We are creating an collection from this array by using “collect()” method, after that we are implementing “map()” function in that collection to filter through every array element and make it UPPERCASE and rejecting any NULL value. So are are getting so much flexibility after using Laravel Collection over typical array manipulation.

 

As Laravel Documentations said, Collections are “Macroable“. So we can add additional methods to the “Collection” class at runtime. This macro method accept a closure. In this closure, we can call other collection collection by using $this keyword.  Lets see an example.

[php]

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Collection::macro(‘toUpper’, function () {
return $this-&amp;gt;map(function($value) {

return Str::upper($value);
});
});

$collection = collect([‘john’, ‘doe’]);
$upper = $collection-&amp;gt;toUpper();

// OUTPUT: [‘JOHN’, ‘DOE’]

[/php]

 

How to Create a Laravel Collection:

To create a Laravel Collection,  We will use collect() helper method of “Illuminate\Support\Collection” instance. Lets create a collection. 

[php]

$my_laravel_collection = collect([‘apple’, ‘orange’, ‘banana’]);

[/php]

Extending of collections:

We can extend Laravel collections. Laravel Collections are also “macroable”. So that we can apply additional methods in collections run time. For Example:

use Illuminate\Support\Collection;

Collection::macro('multiplyByTwo', function () {

    return $this->map(function($value) {

        return $value * 2 ;

    });

});


$collection = collect([20, 30]);
$upper = $collection->multiplyByTwo();

Output:
// [40, 60]
In the Laravel Collection class, by default there are many available methods. full list with definition can be found here. I will just explain these in beginners voice. Below we will show some useful collection methods here.
1. avg(): This method will give us average value of given collection. average() is alias of avg().
return $average = collect([5, 6, 7])->avg(); // 6
2.  chunk(): This method will break a collection in smaller chunks
$collection = collect([1, 2, 3, 4, 5]);

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

$chunks->all(); // [[1, 2, 3], [4, 5]]

3. collapse(): collapse() method combines multiple collections array into a single one.
$collection = collect([
  [1,2,3],
  [4,5,6]
]);

$collapsed = $collection->collapse();
$collapsed->all();

Output:
// [1, 2, 3, 4, 5, 6]
4. collect(): This method return a new colleection from anexisting collection.
$collection_a = collect([1, 2, 3]);
$collection_b = $collection_a->collect();
$collection_b->all();

// [1, 2, 3]

5. combine(): As the name suggest, combine() method combines two or more collections into a single collection.

$collection = collect(['name', 'roll']);

$combined = $collection->combine(['John', 101]);

$combined->all();

Output:
// ['name' => 'John', 'roll' => 101]

6. contains(): This method can be used to find a given value in collection. Such as:

$collection = collect(['John', 'Doe']);
$collection->contains('Doe');
// true

7. count(): As the name suggests, it will give the count of a collection

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

8. dd(): This methods print out collection and end execution of the script. Mostly used for debugging.

$collection = collect(['PHP', 'JavaScript']);
$collection->dd();

Output:
/*

Collection {

#items: array:2 [
    0 => "PHP"
    1 => "JavaScript"
  ]
}

*/

9. diff(): This is a useful collection method to find out differences between two collections. This method will return the values from first collection which are not available in second collection.

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

$diff = $collection->diff([2, 4, 6]);

$diff->all();

// [1, 3, 5]

10. dump(): As simple as it gets. Simply dums the whole collection. Previously mentioned dd() methods do the almost same, but dd() stops the code execution also.

$collection = collect(['John Doe', 'Jane Doe']);

$collection->dump();

/*

Collection {

#items: array:2 [

    0 => "John Doe"

    1 => "Jane Doe"

  ]

}

*/

11. duplicates():

In Laravel, the duplicates() method is used to retrieve the duplicate values from a collection. This method returns a new collection containing the duplicate values found in the original collection.

The duplicates() method can be called on any collection instance, and it takes an optional parameter which specifies the key to check for duplicates. If no key is provided, the method checks for duplicate values in the entire collection.

Here is an example of using duplicates() method on a collection:

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

$duplicates = $collection->duplicates();

// Output: Illuminate\Support\Collection {#3716
// all: [
// 2 => 2,
// 4 => 4,
// ],
// }

 

In this example, the $collection contains some duplicate values, and calling the duplicates() method returns a new collection containing only the duplicate values found in the original collection, which are 2 and 4.

Note that the duplicates() method does not modify the original collection, it only returns a new collection containing the duplicate values.

12. each():

each() method in Laravel Collection iterates through the collection and pass these items by a closure function.

$collection = collect([a, b, c, d]);

$collection->each(function (int $item, int $key) {

    echo "Item $key: $item\n";

});

Output:

Item 0:Item 1:Item 2:Item 3: d

If you want to perform some kind of operation, you can use each() function from collection. Here original collection will be unchanged. If you want to change the original collection, you can use the map() function instead.

13. every():

every() method can be used when you want to make sure your collection can meet certain criteria. TThis method will check that criteria and will return “TRUE” or “FALSE”. Let’s check the example:

collect([11, 12, 13, 14])->every(function (int $value, int $key) {
    return $value > 10;
});

OUTPUT:
// true

Here we are checking a collection with our logic that  if every element of that collection is larger than 10.

14. filter():

The filter() method in Laravel Collection filter the items of an array by filtering these passing through a callback function. For example:

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

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

$filtered->all();

OUTPUT:
// [4, 5]

If no callback function is provided in filter method, it will remove all the false values such as: null,  false,  ”,  0,  [] etc. inverse() method is the opposite of filter() method.

 

15. first(): 

This method is as like as filter method. but it will not return the full data, this method will only return the first element as per the given callback function logic. For example:

collect->first(function ($value, $key) {
    return $value > 3;
});

OUTPUT:
// 4

 

That’s all for today, see you in next  one!

Check Out More Resources:

Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-

WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/

Socials:

Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com

#laravel #guide #php

 

Editorial Staff

A Learner and trying to share what I learned!