when you initially retrieve the model from the database using the first() method, laravel stores the original attributes in the model instance. when you attempt to update the model using the update method, it will use the original attributes unless you reload or refresh the model using the fresh method.
updating model in try/catch : model remembers faulty update values in the catch
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 ?
I see what you mean now. I missread the first question.
when you attempt to update a model's attribute, even if the update operation fails due to a unique constraint violation, laravel updates the model instance's attribute values in memory to reflect the attempted changes. This is a feature of eloquent that allows you to work with the attempted values even if they were not saved to the database.
The #original property shows the values as they were when the model was initially loaded from the database, which includes unique_value as null.
The #attributes property shows the current in-memory values of the model, which reflect the attempted update with unique_value set to 123, even though the update operation failed.
Please or to participate in this conversation.