Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, do..while loop loops infinitely?

Tags:

php

laravel

Right now I have a loop function to work until there are no matches in my database so that I could get a unique string. However, for some reason, my loop is infinite. Is there something I'm doing wrong here?

do {
   $testvar = Str::random(5);
   $data = User::where('password_url', 'LIKE', '%'.$testvar.'%')->get();
}
   while (!empty($data));

The thing is that I do not get any error messages, but I dont get any results as well. Just to reiterate, if my array, $data is empty, I want this loop to be terminated, but if it exists, I want it to continue until it's empty.

like image 652
Udhayan Nair Avatar asked Jun 20 '19 04:06

Udhayan Nair


People also ask

Do while loops laravel 8?

The while loop checks the condition first if true then the code it will be executed. If evaluated to false, the execution will be terminated. The while loop iteration value of the current array element is assigned to $value and the array pointer is moved by one until reaches the last array element.

Do while loop vs while loop PHP?

The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it ...

Do while() PHP?

The PHP do...while LoopThe do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.


1 Answers

Try using $data->count() to check if anything were returned in the result set:

do {
    $testvar = Str::random(5);
    $data = User::where('password_url', 'LIKE', '%'.$testvar.'%')->get();
}
while ($data->count());
like image 59
Tim Biegeleisen Avatar answered Sep 26 '22 11:09

Tim Biegeleisen