Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mick79's avatar

Query still running even after page timeout

I needed to update all of my users with some settings in a new table.

I wrote this:

$users = User::all();

        foreach($users as $u) {
            $settings = Settings::query()->where('user_id', $u->id)->doesntExist();

            if ($settings) {

                $s = new Settings();
                $s->user_id = $u->id;
                $s->show_alltime_stats = 1;
                $s->show_time_listened = 1;
                $s->save();

            }
        }

What I'm trying to do is

  • Get all users from users table.
  • Check if they exist in the settings table.
  • If they don't exist, add them.

Now This was quick and dirty and I didn't use a queue or jobs or anything. just ran this as you see it.

Strange thing after several seconds the page times out, but I noticed the query keeps going. Whats even worse is it took me a few goes to realise this, so users are being created in the settings table multiple times.

Could someone explain to me what madness is going on here? I mean even IF the script were to keep running, I would have thought my code would prevent users being added multiple times.

Any and all help appreciated. I'd like to understand what I've done.

0 likes
6 replies
CorvS's avatar

@mick79 Your page or rather your browser timed out (after 30 seconds are so, depending on your browser), because it was expecting a response after a certain amount of time. That doesn't stop the server request from being processed tho, resulting in your piece of code running completely every time.

It would be more efficient to do that using a query or using SQL on your database directly, that way you don't have to loop over all users and run the settings query every single time.

Mick79's avatar

Thanks @corvs

I probably should have made clear in my OP that I'm a total cowboy 🤘

However what you've said makes absolute sense and I've now learned something and it's not even 10am yet.

1 like
CorvS's avatar

Learning by doing. As long as you didn't do that on a production server nothing happened. 😉

Mick79's avatar

......

pfft.... course I didn't...

Tray2's avatar

You could most likely get away with eagar loading

$users = User::withSettings()->all():
Mick79's avatar

Also a good shout.

Jesus Christ... learned two things already and STILL not even 10am.

Thank you.

Please or to participate in this conversation.