From a04015ac4177dc63186d55eaa0dba5653fbd8f0b Mon Sep 17 00:00:00 2001 From: Hillel Coren Date: Wed, 14 Jun 2017 20:59:44 +0300 Subject: [PATCH] Handle case where public_id has been used --- app/Models/EntityModel.php | 51 +++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/app/Models/EntityModel.php b/app/Models/EntityModel.php index 36220a53b1d2..977f31823a8e 100644 --- a/app/Models/EntityModel.php +++ b/app/Models/EntityModel.php @@ -69,26 +69,32 @@ class EntityModel extends Eloquent $entity->setRelation('user', $user); $entity->setRelation('account', $account); - if (method_exists($className, 'trashed')) { - $lastEntity = $className::whereAccountId($entity->account_id)->withTrashed(); - } else { - $lastEntity = $className::whereAccountId($entity->account_id); - } - if (static::$hasPublicId) { - $lastEntity = $lastEntity->orderBy('public_id', 'DESC') - ->first(); - - if ($lastEntity) { - $entity->public_id = $lastEntity->public_id + 1; - } else { - $entity->public_id = 1; - } + $entity->public_id = static::getNextPublicId($entity->account_id); } return $entity; } + private static function getNextPublicId($accountId) + { + $className = get_called_class(); + + if (method_exists($className, 'trashed')) { + $lastEntity = $className::whereAccountId($accountId)->withTrashed(); + } else { + $lastEntity = $className::whereAccountId($accountId); + } + + $lastEntity = $lastEntity->orderBy('public_id', 'DESC')->first(); + + if ($lastEntity) { + return $lastEntity->public_id + 1; + } else { + return 1; + } + } + /** * @param $publicId * @@ -379,4 +385,21 @@ class EntityModel extends Eloquent { return ''; } + + public function save(array $options = []) + { + try { + return parent::save($options); + } catch (\Illuminate\Database\QueryException $exception) { + // check if public_id has been taken + if ($exception->getCode() == 23000 && static::$hasPublicId) { + $nextId = static::getNextPublicId($this->account_id); + if ($nextId != $this->public_id) { + $this->public_id = $nextId; + return $this->save($options); + } + } + throw $exception; + } + } }