Home > PHP Framework > Laravel > body text

You probably need to know about Laravel collections

藏色散人
Release: 2020-04-08 09:01:23
forward
3226 people have browsed it

Preface

Collections are instantiated through Illuminate\Support\Collection. Laravel's kernel uses collections for most parameter transfers, but this does not mean that collections are good. Laravel is a fast and elegant development framework for a certain reason, not because of its routing, DB, listeners, etc. When you need to process a set of arrays, you may need it to help you solve practical problems quickly.

Recommended: "laravel tutorial"

Creating a collection

$collection = collect([1, 2, 3]);
Copy after login

Obviously, this is a very simple operation. Please stop if you want to say "this operation is complicated", it is more similar to the declaration method in early PHP5.x versions.

$collection = array(1,2,3);
Copy after login

Laravel has not done anything complicated for collection. It will be discussed in the next chapter "Laravel Source Code Analysis Collection". Thank you

Return to the prototype

If you want to convert a collection into data, its use is also very simple

collect([1, 2, 3])->all();
------>
[1, 2, 3]
Copy after login

If performance is not a concern, you can use Laravel collections. After all, it will help you complete 100% of array operations. Ninety percent of work.

For example, we need to cut the array through a horizontal line and divide it into 2 or more arrays. You can use collections to do it~

$collection = collect([1, 2, 3, 4, 5, 6, 7]);
$chunks = $collection->chunk(4);
$chunks->toArray();
// [[1, 2, 3, 4], [5, 6, 7]]
Copy after login

And some methods are designed based on the query method of SQL statements. Let’s take a look at the specific ones.

Method List

Here are some commonly used collection operation methods. Please refer to the official website for details and complete details.

You probably need to know about Laravel collections

Thank you

Thank you for reading this, I hope this article can help you. Thank you, why don't you hurry up and practice gathering?

The above is the detailed content of You probably need to know about Laravel collections. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template