What is a Laravel collection?


What is a Laravel collection? what is a difference between a PHP array and a Laravel collection?

It seems collections are very similar to arrays. For example, result retrieved via the get() method is a collection of data. But when we want to use it as an array we must use toArray() method. Why?

Show source
| php   | laravel   2017-01-04 15:01 2 Answers

Answers to What is a Laravel collection? ( 2 )

  1. 2017-01-04 15:01

    Collection is convenient wrapper for working with arrays of data. Collections have all conveniences of arrays and also bunch of their own helpers.

    The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.


  2. 2017-01-04 18:01

    Think of a Collection as an array on steroids. It is an object that works the same as an array - that is, you can get items with $collection['item'] and set them with $collection['foo'] = 'bar' - but it comes with additional methods for higher-level functions that make common operations easier. These methods are often an alternative for using foreach and manually manipulating arrays. Adam Wathan has some good practical examples of the benefits you might get from using collections instead of arrays. There are also good introductions elsewhere online.

Leave a reply to - What is a Laravel collection?

◀ Go back