PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] How to generate unique Voucher code in laravel 5.2?

 December 29, 2021     laravel-5.2, php     No comments   

Issue

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


Solution

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;
    }


Answered By - dimis283
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing