Laravel, do..while loop loops infinitely?

Viewed 6592

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.

3 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());

You can do using below code too:

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

Why i am suggesting this, is because sometimes $data->count() return wrong count!!

(It has happened to me so at that time i used count() function and it worked!

Have you tried this,

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