Hi, generating a random alpha-numeric code in a model before a save. Before the save occurs though I’d like to check the database to make sure the code is unique. Can I use the rules or do I need to do it another way?
This doesn’t work. What am I doing wrong?
$this->code = randomCode();
You probably need to remove the ! from your while condition, otherwhise you say: Create new code as long as it does not exist in DB.
While i once shared your approach, i’m not sure anymore if it’s really necessary. E.g. just think about how many different hashes are possible with a 32 Byte md5() alone. Even with not very good randomness i believe it will never happen in our lifetimes that you create the same code again (probably not even in the lifetime of the universe…). If you apply a UNIQUE index on your DB, you’ll be save that even in the very very very (…) very seldom case of a duplicate hash, it will not go into your DB.