Eloquent firstOrNew causes a duplicate login error

I am trying to find an item and update it if it exists, or create a new one if it does not exist. However, for some reason, it seems like it is trying to create a new object instead of updating it if it already exists in the database.

    $object = ObjectItem::firstOrNew(array('object_item_id'=>$userEditedObject['object_item_id'], 'object_id'=>$object_id));

    $object->setFields($userEditedObject);

    if($object->save()){
        return TRUE;
    } else {
        return FALSE;
    }

This code creates an error

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '113' for key 'PRIMARY'

This is strange because I used it before, and it worked fine - it looks like it is in this particular case.

+4
source share
1 answer

This means that the $ userEditedObject array contains a duplicate value for the primary key, which is usually "id".

$object , , .

, , , .

+2

Source: https://habr.com/ru/post/1585027/


All Articles