Search code examples
phplaravellaravel-4laravel-5

Laravel: Generate random unique token


I have a table in my database called keys that has this structure:

id | user_id | token_id | token_key

Every time a user logs into my site, I need to generate a new token_id and token_key set for that user. How can I generate a random token for both the token_id and the token_key while keeping the two values unique?

For example, if:

  • token_id is dfbs98641aretwsg,
  • token_key is sdf389dxbf1sdz51fga65dfg74asdf

Meaning:

id | user_id | token_id         | token_key
1  | 1       | dfbs98641aretwsg | sdf389dxbf1sdz51fga65dfg74asdf

There can be no other row in the table with that combination of tokens. How can I do this?


Solution

  • I'd avoid including an extra package for a case like this one. Something like:

    do {
        $token_id = makeRandomToken();
        $token_key = makeRandomTokenKey();
    } while (User::where("token_id", "=", $token_id)->where("token_key", "=", $token_key)->first() instanceof User);
    

    ...should do. Replace model name with yours, if different from 'User', and use your or suggested functions for creating random strings.