Pat Pat - 6 months ago 75
SQL Question

Does the Laravel `increment()` lock the row?

Does calling the Laravel

on an Eloquent model lock the row?

For example:

$userPoints = UsersPoints::where('user_id','=',\Auth::id())->first();
if(isset($userPoints)) {
$userPoints->increment('points', 5);

If this is called from two different locations in a race condition, will the second call override the first increment and we still end up with only 5 points? Or will they add up and we end up with 10 points?


To answer this (helpful for future readers): the problem you are asking about depends on database configuration.

Most MySQL engines: MyISAM and InnoDB etc.. use locking when inserting, updating, or altering the table until this feature is explicitly turned off. (anyway this is the only correct and understandable implementation, for most cases)

So you can feel comfortable with what you got, because it will work correct at any number of concurrent calls:

-- this is something like what laravel query builder translates to
UPDATE users SET points += 5 WHERE user_id = 1

and calling this twice with starting value of zero will end up to 10