php - Laravel 5.1 - Generate a unique 10 alphanumeric character code upon save to database -


i'm working in laravel 5.1 , saving gecko database. code store method below:

public function store(geckorequest $request) {     $user_id = auth::user()->id;     $input = $request->all();      $input['genetics'] = json_encode($input['genetics'], json_force_object);     $input['user_id'] = $user_id;      gecko::create($input);      $name = str_replace(' ', '-', $request['name']);      flash()->success('success!', 'your gecko has been added system');     return redirect()->action('geckocontroller@show', [$name]);  } 

i know $input['uid'] = str_random(10); - how ensure in fact unique , won't redirect form if isn't unique?

is there proper practice achieving this?

create function generates 10 digit random key passes through validator unique rule set. if validator gives error re-run same function generate new one

public function randomid(){       $id = str_random(10);       $validator = \validator::make(['id'=>$id],['id'=>'unique:table,col']);       if($validator->fails()){           $this->randomid();      }       return $id; } 

Comments