Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel PHP foreach(User::all() as $user) performance

if I write a foreach loop like this, is the method all() called every loop again or only once?

foreach(User::all() as $user) { ... }

In C# I know, the all() function is only executed once. But in php also?

Or is it faster if I hold the data in a variable like this?

$users = User::all();
foreach($users as $user) { ...}
like image 786
Phil795 Avatar asked Feb 15 '26 06:02

Phil795


1 Answers

Both pieces of code will do the exactly same job and will create just one DB query, but I'd go with this for better readability:

$users = User::all();
foreach ($users as $user) { ... }
like image 59
Alexey Mezenin Avatar answered Feb 16 '26 20:02

Alexey Mezenin