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]);
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);
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]
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]]
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.
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!