jeudi 14 mai 2020

Generate hundreds of random unique coupon codes and insert in database

I'm using PHP laravel 7 I have a coupons table which has a field called code, and this code is 8 characters (numbers and characters) this code should be unique among coupon records, In admin panel I have a button for admin user, which he can click on and generate as many coupons as he want. I'm gonna share with you the best solution came to my mind and ask you if there is a better and more performant solution.

I'm gonna generate unique strings in my php code using following function :

substr(uniqid(), 0, 8)

then I'll execute a query to check if there is any coupons in my table which it's code is equal to one of my newly generated codes

$model->newQuery()->whereIn('code', $generated_codes)->get();

if the result list is empty, that's nice I'm gonna insert all of my codes in database. if the list is not empty, I'm gonna delete repeated codes from my generated codes, and also again based on number of repeated codes again generate new codes and again repeat the process, I'm gonna repeat the process as long as none of generated codes exist in database then I insert them in database.




Aucun commentaire:

Enregistrer un commentaire