Collections In Laravel In Simple Way

gurpreetkait

Robin Dev

Posted on May 5, 2023

Collections In Laravel In Simple Way

Hi readers, Today we are going to learn about Collections, In Laravel, Collections are a way to manipulate your arrays and play with arrays of data. Because of its methods, it makes code very easy to understand and readable.

Introduction

we also have collect() a helper function with that we can play with the array’s data.

We can extend the Illumniate\Support\Collection class in Laravel means we can add our custom methods in collection.

Quick Example Of Collection

I’ll try to show it as simple as possible.

I have created a route /in CollectionController and now let’s see the quick example of collections in index the method.

public function index()
    {
        $myArr = [1,2,3,4,5,6,7,8,9,10];

        $collection = collect($myArr);
        $collection = $collection->chunk(3);
    }
//Result:
// Illuminate\Support\Collection {#288 ▼ // app/Http/Controllers/CollectionController.php:15
        // #items: array:4 [▼
        // 0 => Illuminate\Support\Collection {#283 ▼
        // #items: array:3 []
        // #escapeWhenCastingToString: false
        // }
        // 1 => Illuminate\Support\Collection {#284 ▼
        // #items: array:3 []
        // #escapeWhenCastingToString: false
        // }
        // 2 => Illuminate\Support\Collection {#286 ▼
        // #items: array:3 []
        // #escapeWhenCastingToString: false
        // }
        // 3 => Illuminate\Support\Collection {#287 ▼
        // #items: array:1 []
        // #escapeWhenCastingToString: false
        // }
        // ]
        // #escapeWhenCastingToString: false
        // }
Enter fullscreen mode Exit fullscreen mode

In the above method, we are using collect() helper function to convert the array to collection format. And by using the $collection variable we are performing a chunk() method on it to make the chunk of three items. It will take three items from the array to convert them into an array that only be having three items.

In the same way, you can perform some more actions on the same collection.

For example, You want to get the first array only which chunk of 3 items.

$collection->chunk(3)->first();

// Illuminate\Support\Collection {#283 ▼ // app/Http/Controllers/CollectionController.php:15
        // #items: array:3 [▼
        // 0 => 1
        // 1 => 2
        // 2 => 3
        // ]
        // #escapeWhenCastingToString: false
        // }
Enter fullscreen mode Exit fullscreen mode

With these examples. I hope you, at least got an idea of what collections do.

Collection Methods

I’m going to explain a few methods that we can use to manipulate the arrays.

Collections in Laravel provide a number of useful methods for working with data. For example, they can be used to filter, sort, group, and transform data. Some of the most commonly used methods include a map, filter, reduce, pluck, groupBy, sortBy, and take.

  1. map: The map method allows you to apply a callback function to each element in a collection and return a new collection with the transformed values. For example, let’s say we have an array of numbers from 1 to 10 and we want to double each element:
$numbers = range(1, 10);
$collection = collect($numbers);
$doubled = $collection->map(function ($num) {
    return $num * 2;
});

Enter fullscreen mode Exit fullscreen mode
  1. filter: The filter method allows you to create a new collection that contains only the elements that pass a certain condition. For example, let’s say we want to create a new collection that contains only the even numbers from our original array:
$evens = $collection->filter(function ($num) {
    return $num % 2 == 0;
});

Enter fullscreen mode Exit fullscreen mode
  1. reduce: The reduce method allows you to apply a callback function to each element in a collection and accumulate a single result. For example, let’s say we want to calculate the sum of all the numbers in our original array:
  public function index()
    {
        $myArr = [1,2,3,4,5,6,7,8,9,10];

        $collection = collect($myArr);
        $total = $collection->reduce(function ($carry, $num) {
            echo $carry . ' + ' . $num . ' = ' . ($carry + $num);
            echo '<br>';
            return $carry + $num;
        }, 0);
        dd($total);
    }
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7 = 28
28 + 8 = 36
36 + 9 = 45
45 + 10 = 55

Enter fullscreen mode Exit fullscreen mode
  1. pluck: The pluck method allows you to extract a single value from each element in a collection and return a new collection with those values. For example, let’s say we have an array of objects representing users and we want to create a new collection that contains only their email addresses:
  public function index()
    {
        $users = [
                ['name' => 'John', 'email' => 'john@example.com'],
                ['name' => 'Jane', 'email' => 'jane@example.com'],
                ['name' => 'Bob', 'email' => 'bob@example.com'],
        ];
        $collection = collect($users);
        $emails = $collection->pluck('email');
        dd($emails);
    }
Enter fullscreen mode Exit fullscreen mode
  1. groupBy: The groupBy method allows you to group the elements in a collection by a certain key or property. For example, let’s say we have an array of users and we want to group them by their age:
 public function index()
    {
        $users = [
            ['name' => 'John', 'age' => 25],
            ['name' => 'Jane', 'age' => 30],
            ['name' => 'Bob', 'age' => 25],
            ];  
        $collection = collect($users);
        $grouped = $collection->groupBy('age');
        dd($grouped);
    }
Enter fullscreen mode Exit fullscreen mode
  1. sortBy: The sortBy method allows you to sort the elements in a collection by a certain key or property. For example, let’s say we have an array of users and we want to sort them by their name:
 public function index()
    {
        $users = [['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Bob', 'age' => 25],
];
$collection = collect($users);
$sorted = $collection->sortBy('name');
    dd($sorted->values()->all());
    }
Enter fullscreen mode Exit fullscreen mode

There are many methods in Laravel, that can help you not to use a series of Foreach and just do things using handy methods.

Now I’m assuming that you understood the collections. You can watch the below video which will take you one step ahead.

This video was created By Povilas From LaravelDaily

See all collection methods: Laravel Collection Methods

You also can read: DB Transactions

Conclusion

Overall, collections are a powerful tool in Laravel that can help you write more expressive and efficient code, and simplify many common data processing tasks.

The post Collections In Laravel In Simple Way appeared first on Larachamp.

💖 💪 🙅 🚩
gurpreetkait
Robin Dev

Posted on May 5, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related