php - Mass insert get duplicate and continu -


i'm using laravel , i'm trying massive insert :

    try {         foreach ($users $key => $user) {             db::table('users')->insert(                 [                     'name' => $user->user_name,                     'email' => $user->user_email,                 ]             );         }      } catch (\exception $e) {         //something     } 

so $users big array , insert each element. have unique constraint on field email, so, if have in array multiple same emails, error "duplicate entry" , query stop.

how can continu insertion if have duplicate entry ? can ignore them ? (and them debug)

thanks !

you can use try\catch , catch illuminate\database\queryexception.

try{     db::table('users')->insert(         [             'name' => $user->user_name,             'email' => $user->user_email,         ]     ); } catch(illuminate\database\queryexception $e) {     //i want consume , continue, nothing here. } 

an error code provided through $e, , 1062 duplicate key warning. can inside of catch block.

catch (illuminate\database\queryexception $e){     $errorcode = $e->errorinfo[1];     if($errorcode == 1062){         // houston, have duplicate entry problem     } } 

credit catch functionality here


Comments