Anirudh Lou
Anirudh Lou

Reputation: 831

How to use save() method for create and update in Eloquent?

I have this object in form of array:

[{"id":"2","passport_number":"AB-2019-11-24-0200","place_issue":"Yuan","date_issue":"2018-10-10","date_expiry":"2018-10-10"}]

and i am trying to save it via save() method of laravel eloquent, here is how it looks:

private function save_person_passport($object, $person_id, \App\Passport $passport){
    if($object->id > 0){
        $passport->id = $object->id;
    }
    $passport->person_id = $person_id;
    $passport->passport_number = $object->passport_number;
    $passport->place_issue = $object->place_issue;
    $passport->date_issue = $object->date_issue;
    $passport->date_expiry = $object->date_expiry;

    $passport->save(); 
}

I am wondering why i am getting this error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2' for key 'PRIMARY' (SQL: insert into `passports`

Isn't save() method use for create and update?

Upvotes: 1

Views: 52

Answers (2)

Chetan Patel
Chetan Patel

Reputation: 26

Try this:

private function save_person_passport($object, $person_id, \App\Passport $passport){
if($object->id > 0){
    $passport = \App\Passport::find($object->id);
      if(!empty($passport){
        $passport->person_id = $person_id;
        $passport->passport_number = $object->passport_number;
        $passport->place_issue = $object->place_issue;
        $passport->date_issue = $object->date_issue;
        $passport->date_expiry = $object->date_expiry;
        $passport->save(); 
      }
    } 
 }

Upvotes: 0

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

You're creating a new instance of \App\Passport so it'll save the record not update. You may do one thing find the id if $object->id > 0

Replace your code the same as below I mention will work for you.

if($object->id > 0){
    $passport = \App\Passport::find($object->id);
    $passport->id = $object->id;
}
$passport->person_id = $person_id;
$passport->passport_number = $object->passport_number;
$passport->place_issue = $object->place_issue;
$passport->date_issue = $object->date_issue;
$passport->date_expiry = $object->date_expiry;

$passport->save(); 

Now if $object->id > 0 then it'll find the collection of Passport. And update the record which primary key is 2

Upvotes: 1

Related Questions