如何在刷新Laravel App Page时避免多次插入相同的数据

时间:2017-08-12 04:42:43

标签: php laravel

刷新Laravel Web应用程序用户插入页面时,如何防止多次在数据库中插入相同的数据。我生成唯一用户ID。但有时我的互联网连接丢失并尝试连接。数据以相同的用户ID插入两次。如何避免它。

public function savenewusers(Request $request){

    $data=$_POST;   

    $usersid = Auth::user()->id;

    $this->validate($request, ['name' => 'required','email'=>'required','role'=>'required','password'=>'required','useraddress'=>'required','district'=>'required']);   

    $userslastcount=User::OrderBy('id','DESC')->first();

    if(count($userslastcount) > 0){
    $uniqid=$userslastcount->uniqueid+1;
    $userid="EF000".$uniqid;    
    } else {
    $uniqid=1;
    $userid="EF000".$uniqid;
    }  

    if(isset($data['managerid'])){
    $managerid=$data['managerid'];      
    } else {
    $managerid="";      
    }

    $password=Hash::make($request->password);

    $createUsers=User::create(['name'=>$data['name'],'email'=>$data['email'],'password'=>$password]);

    $updateUsers=User::Where('id',$createUsers->id)->update(['userid'=>$userid,'officemobileno'=>$data['officemobileno'],'useraddress'=>$data['useraddress'],'district'=>$data['district'],'personalmobileno'=>$data['personalmobileno'],'personalemail'=>$data['personalemail'],'role'=>$data['role'],'managerid'=>$managerid,'uniqueid'=>$uniqid,'enable'=>1]);

    alert()->success('User Created Successfully.', 'Success!'); 

    return redirect('users');       


    }

1 个答案:

答案 0 :(得分:0)

您可以使用firstOrCreate

$user = User::firstOrCreate(['name'=>$data['name'],'email'=>$data['email'],'password'=>$password]);

if ($user->wasRecentlyCreated) {

}