Reputation: 4248
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
Upvotes: 2
Views: 17812
Reputation: 1012
use Illuminate\Support\Str;
$random = Str::random(6);
"emPK39"
Upvotes: 1
Reputation: 61
private static function generateNumber()
{
$number = Str::random(9);
if (self::where('number', $number)->count() > 0) self::generateNumber();
return $number;
}
Upvotes: 6
Reputation: 17658
You can use Laravel's built-in helper method str_random
which generate a more truly "random" alpha-numeric string as:
str_random(6)
The
str_random
function generates a random string of the specified length. This function uses PHP'srandom_bytes
function.
So your final code will be as:
$voucher->code = str_random(6);
Upvotes: 2
Reputation: 222
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;
}
Upvotes: 7
Reputation: 18557
Here is this code
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$code = "";
for ($i = 0; $i < 6; $i++) {
$code .= $chars[mt_rand(0, strlen($chars)-1)];
}
Replace your this line in your code with
$voucher->code = $code;// it should be dynamic and unique
I hope this will work
EDIT
You can try other ways too
$code = strtoupper(uniqid()); // if you dont have any restriction on length of code
For length constraint try this
function generateCouponCode($length = 6) {
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$ret = '';
for($i = 0; $i < $length; ++$i) {
$random = str_shuffle($chars);
$ret .= $random[0];
}
return $ret;
}
Upvotes: 1