Multiply collections to fake bulk data in Laravel
A lot of time when working with UIs, we need a big amount of data to check if the UI is working as expected in a real-world scenario.
But what happens is in your local environment, you might not have enough data to test the UI. For instance, if you’re using collections in Laravel, it might be the case that the collection is too small to test the UI.
This is where this newly added method called multiply
comes in handy.
The method essentially multiplies the content of a collection by a given number. This means if you have a collection with 10 items, and you multiply it by 2, you will get 20 items in the resulting collection.
Here’s an example.
$collection = collect([1, 2, 3, 4, 5]);
$multipliedCollection = $collection->multiply(2);
dd($multipliedCollection);
// [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
This works even for lazy collections.
Like I said, this is something you might not use in production (atleast I’m not able to find a use case for it), but it’s a handy tool when you want to test a UI that uses collections or fake in unit tests.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.