Skip to content

Commit 93c8e94

Browse files
author
Marius
committed
improve increment to reflect atomic operations and also avoid float memory storing issues caused by simple addition or subtraction in laravel incrementOrDecrement model function
1 parent 5b3a658 commit 93c8e94

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/Models/BaseModel.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ abstract class BaseModel extends Model
3131
protected $hidden = [
3232
'laravel_through_key'
3333
];
34+
private array $incrementsToRefresh = [];
3435

3536
/**
3637
* @inheritdoc
@@ -280,4 +281,40 @@ protected function setKeysForSaveQuery($query)
280281
{
281282
return $query->where($this->getPrimaryKeyFilter());
282283
}
284+
285+
/**
286+
* @inheritDoc
287+
*/
288+
public function getAttribute($key)
289+
{
290+
if ($this->exists && isset($this->incrementsToRefresh[$key])) {
291+
$this->attributes = \array_merge(
292+
$this->attributes,
293+
(array)($this->setKeysForSelectQuery($this->newQueryWithoutScopes())
294+
->useWritePdo()
295+
->select(\array_keys($this->incrementsToRefresh))
296+
->first()
297+
?->toArray())
298+
);
299+
$this->incrementsToRefresh = [];
300+
}
301+
302+
return parent::getAttribute($key);
303+
}
304+
305+
/**
306+
* This will mass update the whole table if the model does not exist!
307+
* @inheritDoc
308+
* @throws \InvalidArgumentException
309+
*/
310+
protected function incrementOrDecrement($column, $amount, $extra, $method): int
311+
{
312+
$return = parent::incrementOrDecrement($column, $amount, $extra, $method);
313+
314+
if ($this->exists) {
315+
$this->incrementsToRefresh[$column] = true;
316+
}
317+
318+
return $return;
319+
}
283320
}

0 commit comments

Comments
 (0)