Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the common collection method of laravel

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

The main content of this article is to explain "what is the common collection method of laravel". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the common collection method of laravel"?

The common collection methods of laravel are: filter (), search (), chunk (), dump (), map (), zip (), whereNotIn (), max (), pluck (), each (), tap (), pipe (), contains (), and so on.

The operating environment of this tutorial: windows7 system, Laravel6 version, Dell G3 computer.

Common methods of Laravel set (Collection)

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 parameters in the callback.

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

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

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

Search ()

The search method can find the collection with a given value. If this 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'); / / 2

The search method uses loose comparisons by default. You can use strict comparison by passing true in its second parameter.

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

$names = collect (['Alex',' John', 'Jason',' Martyn', 'Hanlin']); $names- > search (function ($value, $key) {return strlen ($value) = = 6;}); / / 3

Chunk ()

The chunk method splits the collection into a number of smaller sets of a given size. It is useful to display the collection in the grid.

$prices = collect ([18, 23, 65, 36, 97, 43, 81]); $prices = $prices- > chunk (3); $prices- > toArray ()

The above code generation effect.

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

Dump ()

The method by which dump prints collections. It can be used to debug and find the contents of the collection anywhere.

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

Dump the result of the above code.

Map ()

The map method is used to traverse the entire collection. It accepts a callback as a parameter. Value and key are passed to the callback. Callbacks can 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 ()

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"]]

Zip ()

The Zip method combines the values of the given array with the values of the collection. The 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. Here, I will use the collection we just created above. The same applies to Eloquent collections.

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

The JSON response will look like this.

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

WhereNotIn ()

You can use the whereNotIn method to simply filter the collection by keys that are not included in a given array. It is basically the opposite of whereIn. In addition, this method uses loose comparison = = when matching values.

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

$collection- > whereNotIn ('user_id', [1,2])

The above statement will return only the last item in $collection. The first parameter is the key and the second parameter is the value array. If it is eloquent, the first parameter will be the name of the column and the second parameter will be an array of values.

Max ()

The max method returns the maximum value of the given key. You can find the largest user_id by calling max. It is usually used for comparisons such as prices or any other number, but for demonstration purposes, we use user_id. It can also be used for strings, in which case Z > a.

$collection- > max ('user_id')

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

Pluck ()

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

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

The result looks like this.

["Helpers in Laravel", "Testing in Laravel", "Telegram Bot"]

When using eloquent, you can pass the column name as a parameter to extract the value. Pluck also accepts the second parameter, which can be another column name for the collection of eloquent. It will result in a collection of keys with the value of the second parameter.

$title = $collection- > pluck ('user_id',' title'); $title- > all ()

The results are as follows:

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

Each ()

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

$collection- > each (function ($item, $key) {info ($item ['user_id']);})

The above code only records the user_id of each item.

When you iterate through the eloquent collection, you can access all column values as item properties. Here is how we iterate over all posts.

$posts = App\ Post::all (); $posts- > each (function ($item, $key) {/ / Do something})

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

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

Tap ()

The tap () method allows you to join the collection at any time. It accepts the callback and passes the collection to it. You can do anything with 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 ()

In the tap method used above, we modified the collection and then recorded the value. You can do whatever you want with the collections 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"]]

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

Pipe ()

The pipe method is very similar to the tap method because they are used in the collection pipeline. The pipe method passes the collection to the callback and returns the result.

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

The response to the above command is 1. If you return a collection instance from a pipe callback, you can also link to other methods.

Contains ()

The contains method simply checks whether the collection contains the given value. This only happens when only one parameter is passed.

$contains = collect (['country' = >' USA', 'state' = >' NY']); $contains- > contains ('USA'); / / true$contains- > contains (' UK'); / / false

If you pass a key / value pair to the contains method, it checks whether the given key-value pair exists.

$collection- > contains ('user_id',' 1'); / / true$collection- > contains ('title',' Not Found Title'); / / false

You can also pass the callback to the callback method as an argument. A callback will be run on each item in the collection, and if any of the items pass the truth test, it will return true otherwise it will return false.

$collection- > contains (function ($value, $key) {return strlen ($value ['title'])

< 13;});// true 回调函数接受当前迭代项和键的两个参数值。 这里我们只是检查标题的长度是否小于 13。在 Telegram Bot 中它是 12,所以它返回 true。 forget() forget 只是从集合中删除该项。 您只需传递一个键,它就会从集合中删除该项目。 $forget = collect(['country' =>

'usa',' state' = > 'ny']); $forget- > forget (' country')-> all ()

The response from the above code is as follows:

["state" = > "ny"]

Forget does not apply to multidimensional arrays.

Avg ()

The avg method returns the average. All you have to do is pass a 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')

The above code returns 30, which is the average of all four numbers. If you do not pass any 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 a parameter and the collection contains key / value pairs, the avg method returns 0.

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

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 project.

At this point, I believe that you have a deeper understanding of "what is the common collection method of laravel?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report