15 Awesome Laravel Collections Methods. When querying a database in Laravel Eloquent, the result is always returned as collections. Collections are an abstraction that contains very useful methods to make it easier to work with datasets. With collections, you can filter data, concatenate arrays for one specific key, or perform various arithmetic operations. In this article, I’ll take a look at the methods that are contained in Laravel collections – their full power and utility. And the idea of this article appeared after an article was created on working with the main helpers of the framework.
By the way, collections are not any special part of Eloquent. They can also be used separately, with their own data set. To create a collection, you can simply call the helper to collect()bypassing your data array as an argument. All the methods that will be listed below are applicable to Eloquent collections and your own to the same extent.
Let’s pretend you have a model Project. And you need to find all projects where status equals success…
$projects = Project::where(‘status’, ‘success’)->get();
By running this code, you will get a collection of objects from models Project… A collection is a framework class that uses the original arrays internally and adds a lot of additional functionality to them.
This was an example of how to get a model from Eloquent, but in order to create your own collection, simply call the helper to collect()passing the data to it.
$projects = Project::where(‘status’, ‘success’)->get();
In fact, the array $dataabove is a representation of the model data Project. For this article, I will use this particular array for clarity. But you must remember that all the operations that I will show are equally applied to Eloquent collections as to explicitly created ones.
This is how easy you can create collections. This article will cover the most commonly used collection methods. You can see the list of all available methods in the official documentation.
When we use Eloquent collection methods, they do not query the database. All operations are performed with previously obtained data from the database. All results are first retrieved and the database, then a collection is created based on the received data, and at this stage, we already use methods for working with this data, already without any queries to the database.
- filter ()
- search ()
- chunk ()
- dump ()
- zip ()
- whereNotIn ()
- max ()
- pluck ()
- each ()
- tap ()
- pipe ()
- contains ()
- forget ()
- avg ()
Table of Contents
Filter ()
Method filter()is one of the most useful methods in Laravel collections, which allows you to filter data from a collection by callback. This method returns only the data to which the callback returned a value true, the rest of the data will be removed from the collection. The method filter()returns a new collection object based on the filtered data but does not modify the original object’s data.
This pattern is called Prototype, which does not change the original data, but returns a new instance of the object for each method call. As a result, you can have access to both the original data and the filtered/modified data. If the principle from this pattern was not observed, then you would always work with one object, and when the data changed, the same data would change in all places where it is used.
The method callback filter()takes 2 parameters: $value and $key:
$result = $collection->filter(function($value, $key) {
return $value[‘status’] === ‘success’;
})->all();
The method all()returns an array obtained after applying the filter. After executing the code above, we got the following object:
Search ()
The method is search()used to search the collection by a given value. If this value is in the collection, then the key of this value will be returned. If no match is found, it will be returned false.
$collection = collect([‘Sergey’, ‘Alexander’, ‘Denis’, ‘Vasiliy’]);
$result = $collection->search(‘Dima’); // false
$result = $collection->search(‘Alexander’); // 1
By default, searches are performed using a loose comparison. You can pass a value true as the second argument to this method for a strict comparison.
Also, in addition to primitive comparison of values, you can pass a search()callback to the method . As a result, after executing the method, it will return the key of the first value that passed the check:
$result = $collection->search(function($value, $key) {
return strlen($value) === 6;
}); // 0
Chunk ()
The method is chunk()used to split a collection into several smaller collections of a given size. This technique is often used to display a collection as a grid.
$collection = collect([‘Sergey’, ‘Alexander’, ‘Denis’, ‘Vasiliy’]);
$chunks = $collection->chunk(2);
$result = $chunks->toArray();
As a result, we have a result of the form:
And here is the result if you apply this method to the original array with projects:
Dump ()
The method dump()prints information about the data that is in the current collection. This is useful for debugging or viewing collection content anywhere in your application.
$collection
->whereIn(‘id’, [1, 3])
->dump();
Map ()
The method is a map()used to iterate over each of the elements. This method takes as an argument kalbek, which gets the value and the key value, key. This callback has the ability to modify data and return modified versions of the data. As a result, a new collection of your data will be returned, taking into account the modifications made.
$modified = $collection->map(function($value, $key) {
$value[‘id’] += 10;
return $value;
});
$result = $modified->all();
As a result, we get the following answer:
Zip ()
The method zip()adds the values of the passed array to the collection data. The values that you pass will be added at the same index as the collection value, which means that the first value of the passed array will be merged with the first value from the collection.
$zipped = $collection->zip([10, 20, 33]);
$result = $zipped->all();
And the result will be like this:
And that’s all he does. Of course, this method works best when adding data to a regular array, rather than an associative one. If the number of items in the passed array is less than the number of items in the collection, Laravel will add the missing null items to the end of the collection. Also, if the number of items in the array is greater than the number of items in the collection, Laravel will add null for each item in the collection, following the last.
WhereNotIn ()
You can use the method whereNotIn()to filter the collection by the key value that is not contained in the collection. This method is the complete opposite of the method whereIn(). In addition, this method uses loose comparison ==when matching values.
For example, to get all values from a collection, excluding records with IDs 2 and 3:
$values = $collection->whereNotIn(‘id’, [2, 3]);
$result = $values->all();
And we get the filtered result:
This construction indicates that you need to return values from the collection, for which the value under the key is not included in the array of the specified values. The name of the key (field name) by which the check is performed is indicated by the first argument, and the second argument is an array of these identifiers by which records will be excluded.
Max ()
The method max()returns the maximum value that exists in the collection under the specified key. For example, you can thus find the maximum identifier id that exists in this collection. Usually, of course, this method is used for such things as getting the maximum price or some characteristics, but to demonstrate how the method works, let’s just use it id. The method can also be used with strings, in this case, the comparison is performed according to the algorithm Z > a.
$maxId = $collection->max(‘id’); // 3
Pluck ()
The method pluck()returns an array of values for only one specific key. This is useful when extracting only one column of values and forming a separate array from those values. For example, you need to extract a list of all identifiers id or their header’s title.
// [1, 2, 3]
$result = $collection->pluck(‘id’);
// [‘Parsing proxy for HLTV’, ‘…GG.bet’, ‘…vk.com’]
$result = $collection->pluck(‘title’);
In addition, it is possible to retrieve data, indicating which field the key will be stored in, specifying the name of the value column as the first argument, and the name of the column that will be used as the key:
$result = $collection->pluck(‘title’, ‘id’);
// [1 => ‘…HLTV’, 2 => ‘…GG.bet’, 3 =>’…vk.com’]
$result->all();
Each ()
Method each()is a simple method for iterating over the entire values of a collection. It takes a callback with two arguments: one collection value value, and the key of that item. As with a regular array, the initial key is 0.
$result = $collection->each(function ($item, $key) {
handleProject($item);
//…
});
When working with Eloquent collections, you can access all values in a model by a specified item key. This is how you can iterate over all the elements, performing some kind of logic for each of them.
Project::all()->each(function (Project $project, $key) {
if($project->isNew()) {
$project->sendToCheck(Carbon::now());
} else {
$project->sendToSuccess(Carbon::now());
}
// …
});
If you return false from your callback, then it will stop iterating over the elements.
$collection->each(function($value, $key) {
if($key === 1) {
return false;
}
// …
});
Tap ()
The method tap()allows you to embed in a collection anywhere and get the current version of the data, and somehow process it. This method takes a callback that gets the current version of the collection. You can do whatever you want with the values of the collection; the original collection will not be changed. Thus, you can use the method touch()to do something with the collected data at a specific point without modifying the collection itself.
$result = $collection
->whereNotIn(‘id’, 3)
->tap(function(Collection $collection) {
logStatuses($collection->where(‘status’, ‘success’)->values());
})
->all();
And the result will be as tap()follows (from which you can see that the modification of the collection inside the method did not affect the main collection in any way):
In the method tap(), I modified the collection and then logged it. You can do whatever you want with the collection inside tap().
You can see that the method tap()does not modify the original collection instance. You can find out more information about the helper function tap(), which does not differ from the collection method in its logic.
Pipe ()
The pipe on-principle method is very similar tap()in the sense that they both take as an argument a kalbek that receives the collection. Once executed, the method pipe returns the result.
$result = $collection->pipe(function(Collection $collection) {
return $collection->sum(‘id’);
});
echo $result; // 6
Alternatively, you can return the same collection and continue the call chain:
$result = $collection
->pipe(function(Collection $collection) {
return $collection->whereIn(‘id’, [1, 2, 3]);
})
->pluck(‘status’)
->all();
// [‘success’, ‘success’, ‘working’]
Contains ()
The method contains()checks if the specified value exists in the current collection. In this case, the method contains()returns true or false.
$statuses = [‘working’, ‘success’, ‘error’];
$collection = collect($statuses);
$result = $collection->contains(‘working’); // true
$result = $collection->contains(‘undefined’); // false
If you pass a second argument to the method contains, it will check for the existence of an element with a field value matching the second argument. In other words, then it checks for the existence of a key/value pair in the collection.
$result = $collection->contains(‘title’, ‘Parsing proxy for HLTV’); // true
$result = $collection->contains(‘id’, 1); // true
$result = $collection->contains(‘id’, 100500); // false
You can also pass calbek as an argument. And this callback will be executed for each element from the collection, and if any of them pass the test for truth, it will return true, if not, then false.
$result = $collection->contains(function($value, $key) {
return $value[‘title’] === ‘Parsing proxy for HLTV’ || strlen($value[‘title’]) === 15;
}); // true
Kalbek takes two arguments: the current iteration of the collection item and the key of that item. Here the condition is checked: either the element’s title is Parsing proxy for HLTV, or the title length is 15 characters. You can see that you can combine conditions in any way.
Forget ()
The method forgets ()simply removes the item from the collection. You simply pass in the key of an item and it removes that item from the collection.
$data = [‘limit’ => 10, ‘total’ => 100, ‘name’ => ‘Proxy scrapper’];
$collection = collect($data);
$result = $collection->forget(‘name’); // [‘limit’ => 10, ‘total’ => 100]
$result = $collection->forget([‘name’, ‘total’]); // [‘limit’ => 100]
The method forget()does not work with multi-nested arrays.
Avg ()
The method avg()returns the average of all elements. If your collection consists of primitives – numbers, then the method avg()can be called without an argument. Or, if you calculate the average value of the array elements, then you need to specify the key by which the average value will be calculated. Also, a similar method, which is an alias for avg()is average(), you can use it.
$collection = collect([[‘age’ => 30], [‘age’ => 100], [‘age’ => 50]]);
$result = $collection->avg(‘age’); // 60
If you execute the code above, then the result will be 60, which is calculated based on the sum of all values age, and calculates their arithmetic mean. The second use case for this method is to not pass an argument at all. This method is applicable to a collection of only numeric values:
$collection = collect([10, 20, 30, 40, 50]);
$result = $collection->avg(); // 30
Running this code will return a value 30that is the average of all items.
Summary.
In this article, I have detailed what Laravel collections are and what methods exist in them. I have demonstrated the most commonly used and useful methods that come in handy when working with Laravel collections. In addition to theory, he also showed code examples, demonstrating work with different data types, actually-added values , and arrays. After studying this article, you will be able to navigate and skillfully work with Laravel collections without any problems, you will know how they are written internally and use them skillfully.
For professional services or consultation from GCC Marketing Dubai please Contact Us or call us directly on 00971567300683