Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?