3

please help me to find out the issue.

Sometimes (not always) my following code inserts two records in DB (into user table as well as profile table ),but i am checking before inserting that the "mobile_no" is already exist or not that to make unique mobile number based records.

 static function postData($data) { 

    try {
if (isset($data['number'])) {
    //exist
    $exist = Profile::where('mobile_no', '=', $data['number'])->get(); 
   //print_r($exist);

    if (count($exist) > 0 ) {       
    $user = User::find($exist[0]['user_id']);
    if (isset($data['last_name'])) {
    $user->first_name = $data['first_name'];
    }
    if (isset($data['last_name'])) {
    $user->last_name = $data['last_name'];
    }
     if (isset($data['email'])) {
    $user->email = $data['email'];
    }
    $user->save();
    $proid = $exist[0]['user_id'];
    $profile_result = Profile::find($proid);


    if (isset($data['number'])) {
    $profile_result->mobile_no = $data['number'];
    }
     if (isset($data['birthday'])) {
    $profile_result->dob = $data['birthday'];
    }



    $profile_result->save();
    return $exist[0]['user_id'];
    }else{

    $user = new User();
    if (isset($data['first_name'])) {
    $user->first_name = $data['first_name'];
    }
    if (isset($data['last_name'])) {
    $user->last_name = $data['last_name'];
    }


    $user->save();
    $id = $user->id;
    $profile = new Profile();

    $profile->user_id = $id;

    if (isset($data['mobile_number'])) {
    $profile->mobile_no = $data['number'];
    }
    if (isset($data['birthday'])) {
    $profile->dob = $data['birthday'];
    }
    $profile->save();

    $proid = $profile->user_id;
    $profile_result = $profile::where('user_id', '=', $proid)->get();

    $user_result = $user::where('id', '=', $id)->get();

    $output = array();




    return (string) $id;
    }
    }

    } catch (Exception $ex) 
    {
    return $ex;
    }


    }
jai
  • 547
  • 7
  • 20

1 Answers1

2

Using index UNIQUE for database and it will handle for you. Just remember to handle error properly when trying insert a duplicate key.

Community
  • 1
  • 1
Đào Minh Hạt
  • 2,742
  • 16
  • 20