How to generate unique random value for each user in laravel and add it to database

前端 未结 8 1943
刺人心
刺人心 2020-12-29 08:44

I am developing a event organization website. Here when the user registers for an event he will be given a unique random number(10 digit), which we use to generate a barcode

8条回答
  •  [愿得一人]
    2020-12-29 08:59

    One Solution could be like this:

    use Illuminate\Support\Facades\Validator;
    private function genUserCode(){
        $this->user_code = [
            'user_code' => mt_rand(1000000000,9999999999)
        ];
    
        $rules = ['user_code' => 'unique:users'];
    
        $validate = Validator::make($this->user_code, $rules)->passes();
    
        return $validate ? $this->user_code['user_code'] : $this->genUserCode();
    }
    

    Its generating a random number between 1000000000 and 9999999999. After that, it validates the number against the table. If true then it returns the number, otherwise runs the function again.

提交回复
热议问题