# Laravel Collection


In **Laravel**, a **Collection** is an object-oriented wrapper for working with arrays. Collections provide a wide variety of methods that can be used to manipulate arrays or iterate over data sets in a more expressive and fluid way compared to regular arrays in PHP.

A **Collection** class is part of Laravel's **Illuminate\Support\Collection** namespace and is often used in many of Laravel's built-in features like Eloquent models, database queries, and more.

## Creating a Collection

You can create a collection using the `collect()` helper function. Here's a simple example:

```php
use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 4, 5]);
```

You can also convert arrays, Eloquent results, or any iterable data into collections.

## Key Methods of Collections

Laravel collections come with a large set of methods for working with arrays or objects in a convenient way. Below are some of the most common methods:

1. **`all()`**:
   Returns all the items in the collection as an array.
   
   ```php
   $collection = collect([1, 2, 3]);
   $array = $collection->all(); // [1, 2, 3]
   ```

2. **`average()`**:
   Calculates the average value of the collection.

   ```php
   $collection = collect([1, 2, 3, 4, 5]);
   $average = $collection->average(); // 3
   ```

3. **`map()`**:
   Transforms the collection by applying a callback to each item.

   ```php
   $collection = collect([1, 2, 3]);
   $mapped = $collection->map(function ($item) {
       return $item * 2;
   }); // [2, 4, 6]
   ```

4. **`filter()`**:
   Filters the collection by applying a callback that returns `true` or `false`.

   ```php
   $collection = collect([1, 2, 3, 4, 5]);
   $filtered = $collection->filter(function ($item) {
       return $item > 3;
   }); // [4, 5]
   ```

5. **`reduce()`**:
   Reduces the collection to a single value by applying a callback.

   ```php
   $collection = collect([1, 2, 3]);
   $sum = $collection->reduce(function ($carry, $item) {
       return $carry + $item;
   }); // 6
   ```

6. **`sort()`**:
   Sorts the collection in ascending order.

   ```php
   $collection = collect([3, 1, 2]);
   $sorted = $collection->sort(); // [1, 2, 3]
   ```

7. **`sortBy()`**:
   Sorts the collection by a specific key or value.

   ```php
   $collection = collect([
       ['name' => 'John', 'age' => 35],
       ['name' => 'Jane', 'age' => 25],
       ['name' => 'Doe', 'age' => 30],
   ]);
   $sorted = $collection->sortBy('age');
   // [['name' => 'Jane', 'age' => 25], ['name' => 'Doe', 'age' => 30], ['name' => 'John', 'age' => 35]]
   ```

8. **`first()`**:
   Returns the first element in the collection that passes a given condition.

   ```php
   $collection = collect([1, 2, 3]);
   $first = $collection->first(); // 1
   ```

9. **`last()`**:
   Returns the last element in the collection that passes a given condition.

   ```php
   $collection = collect([1, 2, 3]);
   $last = $collection->last(); // 3
   ```

10. **`pluck()`**:
    Retrieves a single value from a collection by key.

    ```php
    $collection = collect([
        ['name' => 'John', 'age' => 35],
        ['name' => 'Jane', 'age' => 25]
    ]);
    $names = $collection->pluck('name'); // ['John', 'Jane']
    ```

11. **`contains()`**:
    Checks if the collection contains a given value.

    ```php
    $collection = collect([1, 2, 3]);
    $contains = $collection->contains(2); // true
    ```

12. **`count()`**:
    Returns the number of items in the collection.

    ```php
    $collection = collect([1, 2, 3]);
    $count = $collection->count(); // 3
    ```

13. **`keyBy()`**:
    Reorganizes the collection by using a specific key as the new index.

    ```php
    $collection = collect([
        ['id' => 1, 'name' => 'John'],
        ['id' => 2, 'name' => 'Jane']
    ]);
    $keyed = $collection->keyBy('id');
    // [1 => ['id' => 1, 'name' => 'John'], 2 => ['id' => 2, 'name' => 'Jane']]
    ```

14. **`groupBy()`**:
    Groups the collection items based on a specific key.

    ```php
    $collection = collect([
        ['type' => 'fruit', 'name' => 'Apple'],
        ['type' => 'vegetable', 'name' => 'Carrot'],
        ['type' => 'fruit', 'name' => 'Banana'],
    ]);
    $grouped = $collection->groupBy('type');
    // ['fruit' => [['type' => 'fruit', 'name' => 'Apple'], ['type' => 'fruit', 'name' => 'Banana']], 
    //  'vegetable' => [['type' => 'vegetable', 'name' => 'Carrot']]]
    ```

15. **`toJson()`**:
    Converts the collection into a JSON string.

    ```php
    $collection = collect([1, 2, 3]);
    $json = $collection->toJson(); // '[1, 2, 3]'
    ```

16. **`containsStrict()`**:
    Checks for strict equality of values in the collection.

    ```php
    $collection = collect([1, 2, 3]);
    $contains = $collection->containsStrict(2); // true
    ```

## Chainability

One of the key features of Laravel Collections is their ability to be chained. Since the collection methods return the collection instance, you can chain multiple methods together in a fluent manner:

```php
$collection = collect([1, 2, 3, 4, 5]);

$result = $collection->filter(function ($item) {
    return $item > 2;
})->map(function ($item) {
    return $item * 2;
})->sort();

print_r($result->all()); // [6, 8, 10]
```

## Collections with Eloquent

Laravel collections are often used in combination with **Eloquent models**. When querying the database with Eloquent, the results are returned as a collection instance, allowing you to use all the methods provided by the Collection class.

Example:

```php
$users = User::all(); // Returns a collection of User models

$users->filter(function ($user) {
    return $user->age > 30;
});
```

## Conclusion

Laravel collections are an essential feature for working with arrays and data in Laravel. They provide an expressive, convenient, and powerful set of methods that make working with data easier and more intuitive. Whether you are manipulating arrays, working with database results, or iterating over data, collections enhance your development experience and simplify many common tasks.

