Random key during user creation

Asked

Viewed 52 times

2

In my migration of User owning: name, id, email and authorization key, however, I would like to know whether it is possible to authorization key is created randomly during user creation, this key has to contain 6 characters.

For example, when the user is created, the key automatically receives a hash:

(12hj34 or user/32ej97).

Is there any recourse to it?

2 answers

1

Updating, just integrate to Laravel the gladcodes/keygen repository gladchinda/keygen-php and then call:

return Keygen::numeric(8)->generate();

in a function of Controller users, making the hash is saved in the database.

  • 1

    An alternative is to perform only \Illuminate\Support\Str::random(6) without the need for a third-party lib.

1


The previous answer is good, but if you want to create something alpha number do so:

private function randomId()
{
    $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $hash = substr(str_shuffle($permitted_chars), 0, 6);
    $validator = \Validator::make(['hash' => $hash], ['hash' => 'unique:users,hash']);
    if ($validator->fails()) {
        return $this->randomId();
    }
    return $hash;
}

Also it is interesting you check if the key is unique before inserting in the bank so I like to put a Validator, so I run the function again if the key is already saved and get a valid key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.