I generate unique codes to use them as coupon codes. This is how a coupon code is generated
public function generateCoupon(){
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 6; $i++) {
$res .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $res;
}
To ensure that I don’t have the same code multiple times in DB I check if the generated code exists:
$coupon = $this->generateCoupon();
while($repository->findOneByCode($coupon) != null){
$coupon = $this->generateCoupon();
}
A coupon code is requested by a user and it is assigned to the user until it is used.
What should happen to the coupon when it is used? Now the code is deleted from DB and it can be used again. Is this good practice? Or should I store the code forever? How would you manage your coupons?
You could use an UUID as your coupon code, to ensure uniqueness, or store the coupon code in a record “forever”, marked as used.