If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing. This method is very useful for writing Artisan commands that process thousands of records. For example, let's work with the entire users table in chunks of 100 records at a time:
It will print 1000 rows, but it will do so executing 10 database queries (fetching 100 rows, printing them, fetching the next 100 rows, printing them etc).
I ask you to 100 tins of food from the shop, but you can only carry 10, so you fetch 10 then go back and get another 10, then another 10 until I have the 100
The request was for 100 tins (total records) but you could only carry 10 at a time (memory restriction)