Generating a unique random string for Model properties in Yii2

When building web software applications I sometimes need a way to generate unique random strings. Unique random strings can be used as character keys or tokens to identify database records without having to give away the database records ID number.

I personally use unique random strings to produce clickable links in my “Request lost password” emails. The unique random string can be matched to a user record and the password can be re-created and sent to the user.

In this article I will show you a method of creating unique random strings. Yii2 already has a way of generating random strings but these will not always necessarily be unique, so in cases where they need to be, this method will come in use.

The method I am about to show is named “generateUniqueRandomString”. I would recommend placing this method in a master Model as it is likely that you are going to want to use this method in more than 1 Model and want it exposed to many different Models.

I covered how to create master Models in a previous article which you can read here …

Create a master Model and Controller in Yii2

After you have created the master Model make sure you put the following “use” statement within it …

Now place the following “generateUniqueRandomString” method inside the master Model …

The above code can be explained as follows …

  1. Line 3 – Use the standard Yii2 “generateRandomString” method to generate a random string of characters
  2. Line 5 – IF statement to check whether the random string already exists for the Model, checked against the attribute (or DB column) passed in through the methods parameters
  3. Line 6 – If the random string does not exist already then return the random string
  4. Line 8 – If the random string does exist already, then recursively run the method again and try and generate a different random string that does not already exist

You can use the above method like follows …

The above code shows a book being found and a unique random string being generated for the books “characterKeyString” property. The book is then saved.

The length by default is set to 32 which means it will generate a 32 character unique random string. If you want to change the length just pass in the second parameter as the length you want to generate.

This method is very useful for when it is important that a random string is unique. I have personally used this method in my user creation, lost password request and file storage parts of my web software applications.

17751 Total Views 26 Views Today

6 thoughts on “Generating a unique random string for Model properties in Yii2”

    1. It depends.

      The script will only take a matter of milliseconds to run and the combinations it can produce are huge.

      The script already checks the table for the random entry it produces to prevent duplicates.

      So unless a second user runs the script at the exact same time (down to milliseconds) and the combination the script produces is exactly the same then it will not matter.

      You are right in that locking the tables would prevent a duplicate random string being generated.

      However the chances of that happening are like winning millions on the lottery.

  1. To avoid locking table, an alternative solution can be updating the field in the loop until success (or attempts limit if we can’t distinguish between different SQL errors).

    1. Yes this is a viable solution.

      However the record would have to exist whilst doing this. Which could get complicated on new records.

  2. this is amazing. thanks for the solution. and this is how i used it to generate a 32-bit long unique id for mongo db.

Leave a Reply

Your email address will not be published. Required fields are marked *