Creating "coupon codes" for users

This is a bit specialized… I want to to have automatic “coupon codes” creation for users. The requirement calls for a 6digit number, unique to each user. Ideally, this would be generated at the moment of the account creation.

Looking for an outline on how to best approach this. Thanks.

Sounds like you are effectively looking for a kind of UUID for each user. Actually, you already have some unique properties for each user - their id, user_name, and email fields - the only problem is that these are guessable by the user, and they do not meet your requirements of a 6-digit number.

The most efficient way would be in the database itself, using for example the UUID_SHORT function in MySQL/Maria (https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_uuid-short). The problem is that this does not meet your requirement for a 6-digit number (which, btw, will prevent you from having more than a million users). I don’t believe MySQL has any way to customize the parameters of this function.

You could just do this in PHP, using mt_rand, and then use a while loop to search the database and regenerate the code until uniqueness is satisfied. As long as the number of users is significantly smaller than 1 million, collisions should be rare and so this will be efficient. I’d probably implement this as a model event, specifically the created event on your custom user model.

1 Like

My thoughts on the UUID was to start from a number, say 100000, and then start incrementing by, say, +123(*) for each new user created.

(*) because we want to minimize proximity of identifiers, so that if a user mistypes a digit it will be less likely to type another user’s UUID by mistake. Also, we don’t expect more than 1000 users for the yearly cycle of the application, after which, we can revise the UUID system.

Regarding the model event, that sounds pretty close to what I want. Do you have examples of events in the UF implementation? The Laravel documentation goes too deep into its own architecture and I can’t quite follow (Authenticatable? Event Classes?)

Sure, you can do this, if you don’t mind the UUIDs being easily guessable. If that’s the case, then any one-to-one function from the set of user ids to the set of 6-digit numbers will work just fine. Another idea I had was to use some kind of hashing function, but I don’t know any out-of-the-box hashing functions whose codomain is specifically the 6-digit integers.

Check out the Member model in the extend-user Sprinkle. Notice that our saved event is defined in the LinkMemberAux trait. We then use LinkMemberAux in the model class itself to register the trait and it’s associated events.

1 Like