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

Issue

I’m working in Laravel 5.1 and saving a gecko to a database. My code for my store method is 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 to the system');
    return redirect()->action('[email protected]', [$name]);

}

I know I could do $input['uid'] = str_random(10); – But how do I ensure it is in fact unique and won’t redirect back to my form if it isn’t unique?

Is there a proper practice into achieving something like this?

Solution

Create a function that generates the 10 digit random key then passes it through a validator with a unique rule set. If the validator gives you an error re-run the same function to generate a new one

public function randomId(){

     $id = \Str::random(10);

     $validator = \Validator::make(['id'=>$id],['id'=>'unique:table,col']);

     if($validator->fails()){
          return $this->randomId();
     }

     return $id;
}

Answered By – Mike Miller

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published