Laravel: Generate random unique token

laravel generate random string
laravel generate unique number
how to generate unique random number in php
generate a unique token php
php generate unique number sequence
laravel random password generator
random number generator in laravel
laravel uuid

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


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?

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.

How can I create a unique random string in laravel 5, With your attempt to the problem you could apply the following to ensure a unique code: do { $token = $this->getToken(6, $application_id);  In terms of generating the tokens, you could use one of Laravel’s Helper Functions; str_random(). This will generate a random string of a specified length, e.g str_random(16) will generate a random string of 16 characters (upper case, lower case, and numbers). Depending on how you are using the tokens,

In terms of generating the tokens, you could use one of Laravel's Helper Functions; str_random().

This will generate a random string of a specified length, e.g str_random(16) will generate a random string of 16 characters (upper case, lower case, and numbers).

Depending on how you are using the tokens, do they really need to be completely unique? Given that they will match to a user, or I assume you may be using the token_id and then verifying this against the token_key does it really matter if there is a double up of one of them? - although the chances of this are extremely small!

However, if you do need them to be truly unique you can always use a validator with the unique constraint. Using this package you could also test that the two of them are unique too with unique_with. And then if the validator fails then it generates a new token as needed.

Based off your examples, you would be using str_random(16) for token_id and str_random(30) for the token_key.

Generating a unique token, Or use: $token = Uuid::uuid1()->toString(); // $​token = 'e4eaaaf2-d142-11e1-b3e4-080027620cdd';. In Laravel  Generate unique Laravel Token. Contribute to mustafakhaleddev/laravel-token development by creating an account on GitHub.

You can use a dependency to do this. Dirape laravel-token

Run the command

composer require dirape/token

In your controller use

use Dirape\Token\Token;

You can use it like this:

        'name'             => $data['name'],
        'email'            => $data['email'],
        'password'         => bcrypt($data['password']),
        'token_key' => (new Token())->Unique('users', 'api_token', 60),
        'active'           => 1

How to generate Random token / key?, Hello How to generate 32 bit random token / key in Laravel 5.6? Generating random base64-encoded tokens or strings as API keys. Generating random strings as password salts to hash user passwords. When your application is required to generate very simple random character sequences like those enumerated above, then the Keygen package is a good option to go for.

Following @ivanhoe suggestion... this is what I came up with:-

    $token = new Token;

    //in case there are duplicate
    for ($x = 0; $x < 10; $x ++) {
        $token->access_token = str_random(16);;
        try {
            if ($token->save()) {
        }catch (QueryException $e) {


mustafakhaleddev/laravel-token: Generate unique Laravel , Generate unique Laravel Token. Generate unique Token From Database. generate random string token with function RandomString($size) and $size is the​  In Laravel 5.2, Taylor Otwell introduced TokenGuard class which allows you to authenticate users with tokens. In order to access the protected routes, you just have to make a request with a valid api_token , as a query string or via header, and then return the relevant information, as JSON.

Laravel Random Keys with Keygen ―, A quick guide through using the Keygen package in your Laravel application. Generating random base64-encoded tokens or strings as API keys. Defining Routes for the API; Generate Unique ID for User; Generate Code  The most concise screencasts for the working developer, updated daily. There's no shortage of content at Laracasts. In fact, you could watch nonstop for days upon days, and still not see everything!

How to Generate Random Unique String in Laravel?, laravel generate unique string, laravel generate random string, get random string in laravel, str_random laravel 5 example, laravel str random  By default, Laravel ships with a simple solution to API authentication via a random token assigned to each user of your application. In your config/auth.php configuration file, an api guard is already defined and utilizes a token driver. This driver is responsible for inspecting the API token on the incoming request and verifying that it

API Authentication - Laravel, Note: While Laravel ships with a simple, token based authentication guard, $​table->string('api_token', 80)->after('password') ->unique() ->nullable() ->default(​null); }); to assign random API tokens to each user that registers with your application. When using hashed API tokens, you should not generate your API tokens  Generate a random number using your favourite random-number generator Multiply and divide it to get a number matching the number of characters in your code alphabet Get the item at that index in your code alphabet.

  • do-while loop will keep "doing" as long as the statement in "while" evaluates as true (and it will run at least once, unlike while-do). In this specific example, it will generate token id/key pair, then it will try to find a user in database that has that specific token and key pair. instanceof checks if the result is instance of the User class, meaning that it's checking if such user is found. If it is, do will execute again and make another pair, and so on until it finds no user having the generated pair of token id/key.
  • This is a very bad solution! You should never wish to loop through every record in you database table each time you want to add a new record. You should better use a time based unique string.
  • It is not looping through every record in the table each time a new record is added. Please try understanding the do-while loop.
  • I agree with @Marten. Not a good solution. There are two things wrong with it: First you hit the database every time you create a new token at least once - if the token exists in the db, you hit it again. Second, there is no guarantee of uniqueness. The same key can be inserted into the db by another thread right after you check for its existence and before you insert it on the current thread. Why not use UUID's, which have a high degree of safety when it comes to uniqueness?
  • One possible improvement would be to just try to insert the new tokens instead of SELECTing them. If they're not unique request will fail (assuming the DB is correctly set with unique indices), and you go back into the loop and create a new pair and try again until the operation succeeds. This would guarantee the atomicity of the operation.