2

I have a Laravel-5.8 project that runs cron job schedule

public function handle()
{       
    $client = new Client();
    $res = $client->request('GET','https://api.employees.net/allemployees', [
       'query' => ['key' => 'dfffgggggffffff']
   ])->getBody();

    $clientdatas = json_decode($res->getContents(), true);        

    foreach($clientdatas as $clientdata)
    {         
        Employee::updateOrCreate([
            'employee_code' => $clientdata->staff_id,
        ],
        [
            'first_name'=> $clientdata->first_name,
            'last_name'=> $clientdata->flast_name,
            'other_name'=> $clientdata->middle_name,
        ]);  

        $user = User::updateOrCreate([
            'email'=> $employee->email,
        ],
        [
            'first_name'=> $employee->first_name,
            'last_name'=> $employee->last_name,
        ]);          

         $employee->update(['user_id' => $user->id]);            
    }           
}

The id for each model are auto-increment.

I observed that while the cron job was saving the external data from the api into the mysql database, the auto-increment for Employee model skipped a step at a point. It skipped 97 and moved to 99. However, the User model is okay, it didn't skip.

I observed that it skipped a particular on that the a particular field is empty:

 'last_name'                             => $employee->last_name,

That is last_name

employee table

mysql employee table

How do I resolve it?

Thank you.

mikefolu
  • 1,203
  • 6
  • 24
  • 57
  • Why is this a problem? There can be many reasons why it was skipped, [here](https://stackoverflow.com/a/17620839/9193055) are some examples. – Remul Jun 17 '20 at 11:17
  • 1
    Looks as using `updateOrCreate` that based on `INSERT ... ON DUPLICATE UPDATE` cause to this behavior. https://stackoverflow.com/questions/23516958/on-duplicate-key-auto-increment-issue-mysql – Slava Rozhnev Jun 17 '20 at 11:18

0 Answers0