DEV Community

Morcos Gad
Morcos Gad

Posted on

Lazy Collections in Laravel

Let's take a look at Collection

use Illuminate\Support\Collection;
new Collection([1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Let's use too times with Collection

return Collection::times(100); // [1, 2, 3, ... 98, 99, 100]
Enter fullscreen mode Exit fullscreen mode
$res =  Collection::times(50)->map(fn ($number) => $number * 2)->filter(fn ($number) => $number % 20 == 0); 
dd($res);
/*
    #items: array:5 [▼
       9 => 20
       19 => 40
       29 => 60
       39 => 80
       49 => 100
    ]
*/
Enter fullscreen mode Exit fullscreen mode

what if it is found

Collection::times(1000 * 1000 * 1000);
Enter fullscreen mode Exit fullscreen mode

Now Switching to Lazy Collections Because when you use Collection you will get an error
" Allowed memory size of 536870912 bytes exhausted (tried to allocate 34359738376 bytes) "

$collection = LazyCollection::times(1000 * 1000 * 1000)->filter(fn ($number) => $number % 2 == 0)->take(1000);
return $collection;
Enter fullscreen mode Exit fullscreen mode

Source :-
https://josephsilber.com/posts/2020/07/29/lazy-collections-in-laravel
I hope you enjoyed the code.

Discussion (0)