Php

How to Play with Data Using Laravel Collection Methods

This tutorial explains about how to work with Laravel collection with Eloquent. I will provide all popular methods of laravel collection. You can convert any PHP array data into the collection and vice-versa as well.

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data into Laravel application.

The Laravel Eloquent is used to get the results from the database, but its return response as a collection. You can convert the collection into an array and work with them, But collection has the number of useful methods that help to manipulate the response data.

You can convert any array into laravel collection using collect helper function. You need to pass an array into collect() method, to convert array into Laravel collection. I am taking my previous Laravel 5.6 CRUD Tutorial Using Resource Controller tutorial as an example.

The resource controller route '/employee' return the all employee list. The routes return the response as the collection. We will apply the Laravel collection methods into it to filter and modify the data set. You can get full list of collection methods form Laravel official Collection Docs.

How to Create New Collection Using Array

The Laravel Illuminate\Support\Collection is provides the collect helper method to convert arrays data into collection. This method returns instance of Collection class for the given array. So, You can create collection is as simple as:

$employees = array (
  0 => 
  array (
    'id' => '34',
    'employee_name' => 'Neha',
    'employee_salary' => '29054',
    'employee_age' => '22',
    'profile_image' => 'images/default_profile.png',
  ),
  1 => 
  array (
    'id' => '35',
    'employee_name' => 'Avinash',
    'employee_salary' => '324050',
    'employee_age' => '25',
    'profile_image' => 'images/default_profile.png',
  ),
  2 => 
  array (
    'id' => '36',
    'employee_name' => 'Unity Butler',
    'employee_salary' => '85675',
    'employee_age' => '47',
    'profile_image' => 'images/default_profile.png',
  ),
);
$emp_collection = collect($employees);

The collect() method convert the employee array data into the collection, Now we can apply any of the collection methods to filter and modify them.

filter() – The Filter the Laravel Collection

The filter method help to filter-out the collection based on condition. This method allows you to apply a callback to the collection. The filter() method only return those items that pass a given truth test condition:

/**
 * Use the filter method to get a list of all the employee that age is greater than 50
 */public function filter()
{
 $employees = Employee::all();
 $emps = $employees->filter(function ($value, $key) {
  return $value->age > 50;
 });

 $emps->all();
}

Contains() – The Find Data into The Collection

contains() method help to find the data into collection based on key value. This method checks if the collection contains a given value. It is only true when you pass a single argument. Its return is Boolean value.

public function filter()
{
 $employees = Employee::all();
 $is_exist = $employees->contains('name', 'parvez');
}

It’s not follow ‘strict’ mode, The containsStrict method help to find data in strict mode.

count() – The count the Collection Elements in Laravel

The count() method help to count the collection object. This method returns the total number of employee in the collection:

$employees = Employee::all();
$employees->count();

forget() – The Remove The Object From the Collection in Laravel

The forget() method help to remove an item from the collection. You need to pass a key that will want to remove from the collection:

Related Post
$employees = Employee::all();
$employees->forget('name', 'parvez');

pipe() – Pass The Collection as a Callback

The pipe() method help to pass the collection objects as a parameter to the callback method.

$employees = Employee::all();
$sum_salary = $employees->pipe(function ($employees) {
    return $employees->sum('salary');
});

pluck() – Return the Collection Values Based on Key

The pluck() method help to find the all value of the passed key. You just need to pass key name of object and get the all values of given key name.

$employees = Employee::all();
$salary = $employees->pluck('salary');
});

You can also pass multiple keys,

$employees = Employee::all();
$sub_col = $employees->pluck('name', 'salary');
});

random() – The Random Collection in Laravel

The random() method is use to return the random collection of the given collection

$employees = Employee::all();
$random = $employees->random();
});

reverse() – The Reverse the Collection Element In Laravel

The reverse() method help to reverse the collection items. Its preserving the original keys:

$employees = Employee::all();
$rev = $employees->reverse();
});

search() – The Search Value into Collection

The search() method is use to search the value into the collection and return the key name. If the value is present in the collection, the key of the value is returned. If the value does not matches any item, false is returned.

$employees = Employee::all();
$search = $employees->search('parvez');
});

chunk() – Split The Collection

The chunk() method is use to split the collection into multiple smaller collection. Its useful into the pagination and listing of items.

$employees = Employee::all();
$salary = $employees->chunk(4);
});

map() – Iterate on Each Collection Item

The map() method help to iterate on each collection of item. You can process the each item of collection using callback method. Its return the instance of the collection items.

$emp = $employees->map(function ($value, $key) {
    $value['salary'] += 1;
    return $value;
});
 
});

each() – How to Iterate on Laravel Collection

The each() method help to iterating over the full collection. Its accepts a callback with two arguments, The first one is the collection and second one is the key index.

$employees = Employee::all();
$employees->each(function ($item, $key) {
    // Do something
});

toJson() – Convert The Laravel Collection Into JSON

The toJson() method help to convert the laravel Collection into json.

$employees = Employee::all();
$employees->toJson();

groupBy() – Laravel Collection Group By Items

The groupBy method help to convert the Laravel Collection items into groups by a given key:

$employees = Employee::all();
$employees->groupBy('age');

push() – Laravel PUSH to Collection

The push method help to add the new item into to the end of the collection:

$employees = Employee::all();
$newEmp = array (
    'id' => '36',
    'employee_name' => 'Unity Butler1',
    'employee_salary' => '856751',
    'employee_age' => '46',
    'profile_image' => 'images/default_profile.png',
  )
$employees->push($newEmp);

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories