Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicated records when concurrent requests make within a second in Laravel

Tags:

php

mysql

laravel

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;
    }


    }
like image 846
jai Avatar asked Dec 12 '25 02:12

jai


1 Answers

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

like image 130
Đào Minh Hạt Avatar answered Dec 13 '25 14:12

Đào Minh Hạt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!