Thursday, March 9, 2017

Creating a UID inside Laravel 5, how can I enhance it to drop the probability of collision?

Currently I am creating a UID for my data inside a controller method called randomId. I've pasted the entire method below:

public static function randomId()
{

    $id = str_random(12);

    $validator = Validator::make(
        ['calculation_uid'=>$id],
        ['calculation_uid'=>'unique:calculations,calculation_uid']
    );

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

    return strtoupper($id);
}

Basically generates a 12 digit alpha-numeric code, and then that gets run through the validator to ensure it doesn't already exist; if it does exist it runs the method again.

I know I can reduce the probability of collision by increasing it to say 16 chars but I'll forever be increasing it if I ever hit the limit.

Is there a way I can (for a lack of better phrasing) make this more unique? Or is my implementation likely to be okay?



via Andy Holmes

Advertisement