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 ?