Skip to content
Advertisement

How to generate unique Voucher code in laravel 5.2?

I want to save unique voucher code and mix of characters and numerics and it should be 6 in length. I am using Laravel Framework 5.2

enter code here
$data = $request->all();
        unset($data['_token']);
        //echo "<pre>"; print_r($data); die;
        for ($i=1; $i <=$data['countvoucher']; $i++) { 
            $voucher = new Voucher;
            $voucher->code = "123456";// it should be dynamic and unique
            $voucher->percentage = $data['percentage'];
            $voucher->usage  = $data['usage'];
            $voucher->expirydate = $data['expirydate'];
            $voucher->save();
        }

$voucher->code i want to save in this filed can anyone help me

Advertisement

Answer

I am using this function You may use it like something like bellow

 $voucher->code = $this->generateRandomString(6);// it should be dynamic and unique 

public  function generateRandomString($length = 20) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement