Support the ongoing development of Laravel.io →
posted 9 years ago
Database

Hey folks,

I've built a very simple chat style interface around the system proposed here:

http://tutorialzine.com/2010/10/ajax-web-chat-php-mysql/

I'm facing an issue that I could use a bit of help with. The problem is that some users are being prematurely removed from the chat. In short, when a user joins the chat (anonymously) a record is created in the MySQL database with timestamp. Whenever the browser of this user requests an update, the timestamp associated with the users record is updated. At the same time, an update request will also trigger the system to search for timestamps that are more than 30 seconds in the past and promptly delete any such user record, assuming they've left without logging out properly.

The issue appears to be that occasionally, a users record will be deleted the very moment it is created. As if the record is first created, and then updated with the proper time stamp. I thought that perhaps laravel's save() function on an eloquent model would first create a record and then update it, so I surrounded it with some transaction commands. Didn't help. I've looked at Laravels code and as far as I can tell, it just performs a regular insert when the record has yet to be created.

My code for creating the user record looks thusly:

        $date = new \DateTime;

        $webchatUser = new WebchatUser;

        $webchatUser->wcuUserID = $wcuUserID;
        $webchatUser->wcuName = $wcuName;
        $webchatUser->wcuRegistered = $wcuRegistered;
        $webchatUser->wcuActive = true;
        $webchatUser->wcuLastActivity = $date;

        Log::info('Info | userJoinsWebChat | wcuName: ' . $wcuName . ' | wcuUserID: ' . $wcuUserID);

        \DB::beginTransaction();
        $webchatUser->save();
        \DB::commit();

and the code to remove stale users, looks like this:

$affectedRows = WebchatUser::whereRaw('wcuLastActivity < SUBTIME(NOW(),\'0:0:30\')')->delete();

I'm a bit clueless as for what to do though. I've tried not updating the timestamp, just to see that it's created properly, and sure enough, it looks ok and is promptly deleted after 30 seconds. I would think that a single insert should execute fine, without being interrupted by the delete query on an InnoDB table...?

What am I missing here?

Regards, Gazoo

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Gazoo101 gazoo101 Joined 24 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.