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.
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.
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() 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.
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();
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:
$employees = Employee::all(); $employees->forget('name', 'parvez');
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'); });
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'); });
The random() method is use to return the random collection of the given collection
$employees = Employee::all(); $random = $employees->random(); });
The reverse() method help to reverse the collection items. Its preserving the original keys:
$employees = Employee::all(); $rev = $employees->reverse(); });
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'); });
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); });
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; }); });
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 });
The toJson() method help to convert the laravel Collection into json.
$employees = Employee::all(); $employees->toJson();
The groupBy method help to convert the Laravel Collection items into groups by a given key:
$employees = Employee::all(); $employees->groupBy('age');
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);
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
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
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More