Reputation: 443
I am doing a lucky draw method whereas users can only get the lucky draw when the number of tries hit the certain numbers.
In order to do this, I have a table called gifts, it will save each time the user try to lucky draw. I have created a simple method to do this.
public function canGetLuckyDraw()
{
$gifts = Gift::count();
Gift::create([
'user_id' => auth()->id,
'status' => false
]);
if($gifts % 300 == 0)
{
$this->userGetTheLuckyDraw();
}
}
When the current user is at 300 tries. Then the user will get the lucky draw. The problem is that I found that if both users are accessing the canGetLuckyDraw() method at the same time. There is a chance that the count from gifts table will be the same and two or more users will get the lucky draw.
Anyone knows what is the best way of handling situation like this? I have used queue, but it kinda slow as I am forced to use only 1 worker to handle this to ensure the count is unique.
Upvotes: 0
Views: 57
Reputation: 95
Use where clause and count.
$gifts = Gift::where('user_id', auth()->id)->count();
Upvotes: 1