i have a nested function calls to update some data in database , the column im going to update is unique in database and it may be updated with a duplicate value in that case i want to flag that model/row as duplicated
here is simplified version of my code without the nested function calls
public $defaultModel ;
function errorTest(){
$this->defaultModel = $inprogress = Process::where('inprogress' , 1 )->first();
try
{
$inprogress->update( [
'deployment_id' => 666 ,
]);
}
catch (Exception $exception)
{
$this->defaultModel->update([
'inprogress' => 0 ,
'error'=>'duplicate'
]);
}
}
when i try to update the model with a duplicate value i keep getting laravel error page
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '666' for key
'process_deployment_id_unique'
at first i thought maybe my try/catch isnt working and i cant catch the error , but after playing around i found out the error is caused by catch section
$this->defaultModel->update([
'inprogress' => 0 ,
'error'=>'duplicate'
]);
even though im not updating the unique column (deployment_id)
in the catch , the model is still remembering the value given in the try body and trying to update deployment_id
in the catch with the 666
value
crazy part is im not even using the same variable in the catch section ! it’s like they are referencing each other
the only way around it is to do something like
$model = $this->defaultModel->fresh();
$model->update([
'inprogress' => 0 ,
'error'=>'duplicate'
]);
any idea why is this happening ?
2
Answers
if the value is unique you can’t update it with an existing value, you get the error
is due precisely because you are trying to add a duplicate value, what you could do is remove the unique value from the table column in question, so you can insert duplicate values and then mark them as such
you need to change your approach, first check if that ID exists within the database table, if yes you can mark that entry as duplicate, if no you can update that column value with your ID.