In this tutorial, you’re going to learn about the Laravel collections. Using the Collection, you can manipulate the array with lots of helper functions. To create a new collection instance from the array, you can use collect helper. Laravel provides lots of helper functions to work with. You can check all available methods.
The first thing to remember, all methods needs collections instance before use. Therefore, you need to use collect helper to use in all array results before use. On the other hand, all eloquent query results already come with a collection instance. In that case, you can use any helpers directly into eloquent results. In this tutorial, we will examine important methods.
Post Contents
# How To Use Laravel Collections?
At this moment, let add an example to this. There is a pluck method in available collections. Pluck method returns the array of the given key or column. I’ll use that method in the array and eloquent result.
# Using Collection Method In Array
As discussed above, a collect helper is necessary before using any available methods. For example, let’s assume you have an array like below. You can retrieve the name column using the pluck method like below.
<?php
public function index()
{
$users = [
['name' => 'User 1', 'price' => 10],
['name' => 'User 2', 'price' => 20],
['name' => 'User 3', 'price' => 30],
['name' => 'User 4', 'price' => 40],
['name' => 'User 5', 'price' => 50],
];
$collection = collect($users);
$result = $collection->pluck('name');
dd($result->all());
}
?>
# Using Collection Methods In Eloquent
On the other hand, the eloquent method not required the collect helper. As you can see, you can achieve an identical result without using a collect helper.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class WelcomeController extends Controller
{
public function index()
{
$users = User::all();
$result = $users->pluck('name');
dd($result->all());
}
}
# Using chunk() Method
The chunk method is similar to the array_chunk method in PHP. This method breaks a collection into multiple collections. Chunking is very useful while handling a large amount of data.
# Scenario 1 : chunk() With Large Data
For example, you have a large number of users, let’s assume 10000. By using the chunk method, you can break those records with given digits. Chunking 10000 records in 10 parts will give you 1000 records in each piece of an array.
<?php
public function index()
{
$users = [
['name' => 'User 1'],
['name' => 'User 2'],
['name' => 'User 3'],
['name' => 'User 4'],
['name' => 'User 5'],
// ....
// ....
['name' => 'User 10000'],
];
$collection = collect($users);
$result = $collection->chunk(10);
dd($result->all());
}
?>
You can achieve the following result when using this helper.
<?php
[
[
['name' => 'User 1'],
['name' => 'User 2'],
//......
['name' => 'User 1000'],
],
[
['name' => 'User 1001'],
['name' => 'User 1002'],
//......
['name' => 'User 2000'],
],
// .....
// .....
[
['name' => 'User 9001'],
['name' => 'User 9002'],
//......
['name' => 'User 10000'],
],
];
?>
# Scenario 2 : chunk() In Blade Template
To put it another way, the chunk method is also useful while using it in HTML. To clarify, assuming you have the image collections. In each row, you need to display only 2 images. You can do that in the following way.
@foreach ($images->chunk(2) as $chunk)
<div class="row">
@foreach ($chunk as $image)
<div class="col-xs-6">
<img src="{{ $image->src }}" alt="{{ $image->name }}">
</div>
@endforeach
</div>
@endforeach
# Using diff() Method
The diff method compares given collections and returns different values. The first thing to remember, It will only return the original (or main) collection values.
<?php
public function index()
{
$cars = collect(["Toyota", "Mercedes", "BMW", "Audi"]);
$result = $cars->diff(["Toyota", "Jaguar"]);
dd($result->all());
/* Result */
// [ "Mercedes" , "BMW", "Audi" ]
}
?>
# Using duplicates() Method
As the name suggests, the duplicates method retrieves duplicate values with its keys, with the given collection.
<?php
public function index()
{
$cars = collect(["Toyota", "Mercedes", "BMW", "Audi", "Toyota", "BMW"]);
$result = $cars->duplicates();
dd($result);
/* Result */
//[ 4 => "Toyota", 5 => "BMW" ];
}
?>
# Using max() Method
By using, the max method, you can find the max value of the given collection. Besides, you can find the max value with the given column.
<?php
public function index()
{
$ages = collect([19, 55, 78, 63]);
$result = $ages->max();
echo $result;
/* Result */
// 78
// Or you can find max value by given column
$ages = collect([ ['age' => 19], ['age' => 55], ['age' => 78], ['age' => 63] ]);
$result = $ages->max('age');
echo $result;
/* Result */
// 78
}
?>
# Using min() Method
In the same vein, using the min method will give you the min value of the given collection. Also, you can find the min value with the given column.
<?php
public function index()
{
$ages = collect([56, 85, 63, 47]);
$result = $ages->min();
echo $result;
/* Result */
// 47
// Or you can find min value by given column
$ages = collect([ ['age' => 56], ['age' => 85], ['age' => 63], ['age' => 47] ]);
$result = $ages->min('age');
echo $result;
/* Result */
// 47
}
?>
# Using pop() Method
The pop method removes the last value of the collection. You can get the last value or the remaining collection.
<?php
public function index()
{
$fruits = collect(['Banana', 'Mango', 'Watermelon', 'Grapes']);
$result = $fruits->pop();
echo $result;
/* Result */
// Grapes
//Or you can get remaining collection
$fruits = collect(['Banana', 'Mango', 'Watermelon', 'Grapes']);
$fruits->pop();
dd($fruits->all());
/* Result */
// ['Banana', 'Mango', 'Watermelon']
}
?>
# Using push() Method
In contrast, the push method appends the value in the collection. For example:
<?php
public function index()
{
$fruits = collect(['Banana', 'Mango', 'Watermelon']);
$fruits->push('Grapes');
dd($fruits);
/* Result */
// ['Banana', 'Mango', 'Watermelon', 'Grapes']
}
?>
# Using reverse() Method
The reverse method returns the given collection in the reverse order. Equally important, this method also saves the original keys of the collection.
<?php
public function index()
{
$fruits = collect(['Banana', 'Mango', 'Watermelon']);
$reverse = $fruits->reverse();
dd($reverse->all());
/* Result */
// ['Watermelon', 'Mango', 'Banana']
}
?>
This is it for the laravel collections tutorial. Thank you for reading this tutorial. Please keep supporting. Happy coding 🙂