Laravel Collections

Collections in laravel is a fluent object provided by Illuminate\Support\Collection class. It is used to work with arrays of data more efficiently and fluently. Laravel collections provide a wide range of helpful methods for filtering, transforming, and manipulating array-like data.

Convert Array to Collection

Using collect() helper function we convert the array into collection or we can create a new collection.
Example:

$array = [1, 2, 3, 4, 5, 6, 7];
// Convert array into collection
$collectionA = collect($array);

// Create new collection
$collectionB = $collectionA->collect();
$collectionB->all();
// [1, 2, 3]

Collection Methods

Laravel collections provide a wide range of methods like filtering, mapping, reducing, sorting, transforming, chunking, searching, etc to manipulate data. Here are some examples of that.
Example:

// Creating a collection from an array
    $collection = collect([825, 524, 89, 93, 4882, 7366, 35, 265, 946, 8635]);

    // Sorting collection
    $sortAsc = $collection->sort(); // ascending order
    $sortDesc = $collection->sortDesc(); // descending order
    /* Output:
        $sortAsc = [35, 89, 93, 265, 524, 825, 946, 4882, 7366, 8635]
        $sortDesc = [8635, 7366, 4882, 946, 825, 524, 265, 93, 89, 35]
    */

    // Filter collection
    $filtered = $collection->filter(function ($value, $key) {
        return $value > 1000;
    });
    // Output: [4882, 7366, 8635]


    // Transform collection
    $transformed = $collection->map(function ($item, $key)    {
        return $item * 2;
    });
    // Output: [1650, 1048, 178, 186, 9764, 14732, 70, 530, 1892, 17270]

    // Chunk collection
    $chunks = $collection->chunk(4);
    // Output: [[825, 524, 89, 93], [4882, 7366, 35, 265], [946, 8635]]

Why should we use collection function instead of array function?

Laravel collections offer several advantages over using plain PHP arrays with array functions. For example, to search something into a PHP array we need to loop through an array to search for the record value, instead of that we can use the contains() method of Laravel collection.
Example:

/* PHP LOOP */
  $condition = false;
  foreach ($array as $record) {
      if ($record['name'] == 'John') {
          $condition = true;
          break;
      }
  }

/* Laravel Collections */
$condition = collect($array)->contains(function ($record) {
      return $record['name'] = 'John';
  });
  • Collections allow for method chaining, which eventually enable us to perform multiple operations in a single chain.
  • Also Collections are used to handle results returned from Laravel’s Eloquent ORM or query builder. They allow you to work with query results as a collection of objects.
  • Lazy Collection is a more advanced and powerful form of Laravel’s Collection, which performs operations on items only when they’re accessed. This can significantly improve performance, especially when dealing with large datasets, because it loads once single into memory at a time of operation we perform.

However PHP arrays and array functions have their own place and are still useful. Laravel collections provide an enhanced way to work with data structures. But Choosing between them ultimately depends on the specific use case.

Support On Demand!

                                         
Laravel