This post is from the professional Laravel developer community, original link: learnku.com/laravel/t/2…

Eloquent usually returns as a result a collection that contains many useful and powerful methods. You can easily filter and modify collections. This tutorial will take a look at the common methods and functions of collections. The collection is not limited to the eloquent, but can also be used on its own. But the Eloquent result is a collection. You can use the helper function collect to convert arrays into collections. The collection methods listed below work equally well for eloquent results as they do for the collection itself.

Let’s say you have a post model. You find posts in all PHP categories.

$posts = App\Post::where('category'.'php')->get();
Copy the code

The above command returns a collection. A collection is a Laravel class that uses array functions internally and adds a lot of functionality to them.

You can simply create a collection using the collect method as follows:

$collection = collect([
    [
        'user_id'= >'1'.'title'= >'Helpers in Laravel'.'content'= >'Create custom helpers in Laravel'.'category'= >'php'
    ],
    [
        'user_id'= >'2'.'title'= >'Testing in Laravel'.'content'= >'Testing File Uploads in Laravel'.'category'= >'php'
    ],
    [
        'user_id'= >'3'.'title'= >'Telegram Bot'.'content'= >'Crypto Telegram Bot in Laravel'.'category'= >'php']]);Copy the code

The array above is actually the values of the Post model. In this tutorial, we’ll use this array to simplify things. Remember, everything will be based the same way, eloquent.

When we use helper methods on the Eloquent collection, we do not query the database. We first get all the results from the database, and then we use a collection approach to filter and modify them without querying the database.

filter()

Filter, one of the most useful Laravel collection methods, allows you to filter collections using callbacks. It passes only those items that return true. All other items have been deleted. Filter returns a new instance without changing the original instance. It accepts value and key as two arguments in the callback.

$filter = $collection->filter(function($value.$key) {
    if ($value['user_id'] = = 2) {return true; }});$filter->all();
Copy the code

The all method returns the underlying array. The code above returns the following response.

1 = > ["user_id"= > 2,"title"= >"Testing in Laravel"."content"= >"Testing File Uploads in Laravel"."category"= >"php"]]Copy the code

search()

The search method can find a collection with a given value. If the value is in the collection, the corresponding key is returned. If no data item matches the corresponding value, false is returned.

$names = collect(['Alex'.'John'.'Jason'.'Martyn'.'Hanlin']);

$names->search('Jason'); / / 2Copy the code

The search method uses loose comparisons by default. You can pass true in its second argument using strict comparison.

You can also pass your own callback to the search method. Returns the key of the first item that passes the callback truth test.

$names = collect(['Alex'.'John'.'Jason'.'Martyn'.'Hanlin']);

$names->search(function($value.$key) {
    return strlen($value) = = 6; }); / / 3Copy the code

chunk()

The chunk method splits the collection into smaller collections of a given size. Displaying collections into a grid is useful.

$prices = collect([18, 23, 65, 36, 97, 43, 81]);

$prices = $prices->chunk(3);

$prices->toArray();
Copy the code

The above code generates the effect.

[0 = > [0 = > 18, 1 = > 23, 2 = > 65], 1 = > [3 = > 36, 97, 4 = > 5 = > 43], 2 = > 6 = > [81]]Copy the code

dump()

Dump methods to print collections. It can be used to debug and find the contents of a collection anywhere.

$collection->whereIn('user_id', [1, 2])
    ->dump()
    ->where('user_id', 1);
Copy the code

Dump the above code results.

map()

The map method is used to traverse the entire collection. It accepts a callback as an argument. The value and key are passed to the callback. Callbacks modify values and return them. Finally, a new collection instance of the modified item is returned.

$changed = $collection->map(function ($value.$key) {
    $value['user_id'] + = 1;return $value;
});

return $changed->all();
Copy the code

Basically, it increases user_id by 1.

The response of the above code is shown below.

[["user_id"= > 2,"title"= >"Helpers in Laravel"."content"= >"Create custom helpers in Laravel"."category"= >"php"
    ],
    [
        "user_id"= > 3,"title"= >"Testing in Laravel"."content"= >"Testing File Uploads in Laravel"."category"= >"php"
    ],
    [
        "user_id"= > 4,"title"= >"Telegram Bot"."content"= >"Crypto Telegram Bot in Laravel"."category"= >"php"]].Copy the code

zip()

The Zip method merges the values of the given array with the values of the collection. Values of the same index are added together, which means that the first value of the array is merged with the first value of the collection. In this case, I’ll use the collection we just created above. This works equally well for the Eloquent collection.

$zipped = $collection->zip([1, 2, 3]);

$zipped->all();
Copy the code

The JSON response will look something like this.

So, that’s basically it. If the length of the array is less than the length of the Collection, Laravel adds null to the end of the remaining Collection elements. Similarly, if the length of the array is greater than the length of the Collection, Laravel adds null to the elements of the Collection type, followed by the value of the array.

whereNotIn()

You can use the whereNotIn method to simply filter a collection by key values not contained in a given array. It’s basically the opposite of having by. In addition, this method uses a loose comparison == when matching values.

Let’s filter $collection where user_id is neither 1 nor 2.

$collection->whereNotIn('user_id', [1, 2]);
Copy the code

The above statement will return only the last item in the $collection. The first argument is the key, and the second argument is the array of values. The first argument would be the name of the column, and the second argument would be an array of values.

max()

The Max method returns the maximum value of a given key. You can find the maximum user_id by calling Max. It’s usually used for comparisons like price or any other number, but for demonstration purposes, we’ll use user_id. It can also be used for strings, in which case Z> a.

$collection->max('user_id');
Copy the code

The above statement will return the maximum user_id, which in our case is 3.

pluck()

The pluck method returns all the values of the specified key. It is useful for extracting the values of a column.

$title = $collection->pluck('title');
$title->all();
Copy the code

It’s going to look something like this.

[
  "Helpers in Laravel"."Testing in Laravel"."Telegram Bot"
]
Copy the code

Using eloquent, you can pass the column name as a parameter to extract a value. Pluck also accepts a second parameter, which can be an additional column name for the Eloquent collection. It results in a set of keys with the value of the second parameter.

$title = $collection->pluck('user_id'.'title');
$title->all();
Copy the code

The results are as follows:

[
    "Helpers in Laravel"= > 1,"Testing in Laravel"= > 2,"Telegram Bot" => 3
]
Copy the code

each()

Each is a simple way to iterate over the entire collection. It accepts a callback with two parameters: the item and key it is iterating over. Key is a zero-based index.

$collection->each(function ($item.$key) {
    info($item['user_id']);
});
Copy the code

The above code simply records the user_id of each entry.

You can access all column values as item properties when iterating through the Eloquent collection. Here’s how we iterate over all the posts.

$posts = App\Post::all();

$posts->each(function ($item.$key) {
    // Do something
});
Copy the code

If false is returned in the callback, it stops the iteration project.

$collection->each(function ($item.$key) {
    // Tasks
    if ($key= = 1) {return false; }});Copy the code

tap()

The tap() method allows you to join the collection at any time. It accepts the callback and passes and passes the collection to it. You can do anything to the project without changing the collection itself. Therefore, you can use TAP to join the collection at any time without changing the collection.

$collection->whereNotIn('user_id', 3)
    ->tap(function ($collection) {
        $collection = $collection->where('user_id', 1);
        info($collection->values());
    })
    ->all();
Copy the code

In the TAP method used above, we modify the collection and then record the values. You can do whatever you want with the collection in TAP. The response to the above command is:

[["user_id"= >"1"."title"= >"Helpers in Laravel"."content"= >"Create custom helpers in Laravel"."category"= >"php"
    ],
    [
        "user_id"= >"2"."title"= >"Testing in Laravel"."content"= >"Testing File Uploads in Laravel"."category"= >"php"]]Copy the code

You can see that TAP does not modify the collection instance.

pipe()

The PIPE method is very similar to the TAP method in that both are used in the collection pipe. The PIPE method passes the collection to the callback and returns the result.

$collection->pipe(function($collection) {
    return $collection->min('user_id');
});
Copy the code

The response to the above command is 1. Other methods can also be linked if the collection instance is returned from the PIPE callback.

contains()

The contains method only checks if the collection contains a given value. This happens when only one argument is passed.

$contains = collect(['country'= >'USA'.'state'= >'NY']);

$contains->contains('USA');
// true

$contains->contains('UK');
// false
Copy the code

If you pass a key/value pair to the CONTAINS method, it checks to see if the given key/value pair exists.

$collection->contains('user_id'.'1');
// true

$collection->contains('title'.'Not Found Title');
// false
Copy the code

You can also pass the callback as an argument to the callback method. The callback is run on each item in the collection and returns true if any of the items passes the truth test and false otherwise.

$collection->contains(function ($value.$key) {
    return strlen($value['title']) < 13;
});
// true
Copy the code

The callback takes two parameter values for the current iteration item and key. Here we just check that the title is less than 13 in length. In Telegram Bot it is 12, so it returns true.

forget()

Forget simply removes the item from the collection. You simply pass a key, and it removes the item from the collection.

$forget = collect(['country'= >'usa'.'state'= >'ny']);

$forget->forget('country')->all();
Copy the code

The above code responds as follows:

[
    "state"= >"ny"
]
Copy the code

Forget does not work with multidimensional arrays.

avg()

The AVG method returns the average. You only need to pass one key as an argument, and the AVG method returns the average. You can also use the Average method, which is basically an alias for AVG.

$avg = collect([
    ['shoes'= > 10], ['shoes'= > 35], ['shoes'= > 7], ['shoes' => 68],
])->avg('shoes');
Copy the code

The code above returns 30, which is the average of all four numbers. If you pass no keys to the AVG method and all items are numbers, it will return the average of all numbers. If the key is not passed as an argument and the collection contains key/value pairs, the AVG method returns 0.

$avg = collect([12, 32, 54, 92, 37]);

$avg->avg();
Copy the code

The above code returns 45.4, which is the average of all five numbers.

You can use these Laravel collection methods to work with collections in your own projects.