我想保存独特的优惠券代码以及字符和数字的组合,它应该是6个长度。我正在使用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-&gt;代码我想保存在此档案中,任何人都可以帮助我
答案 0 :(得分:3)
我正在使用此功能 你可以像下面的那样使用它
$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;
}
答案 1 :(得分:2)
您可以使用Laravel的内置辅助方法https://tomcat.apache.org/tomcat-8.0-doc/config/ajp.html来生成更真实的&#34;随机&#34;字母数字字符串为:
str_random
random_bytes
函数生成指定长度的随机字符串。此函数使用PHP的$voucher->code = str_random(6);
函数。
所以你的最终代码将是:
{{1}}
答案 2 :(得分:2)
private static function generateNumber()
{
$number = Str::random(9);
if (self::where('number', $number)->count() > 0) self::generateNumber();
return $number;
}
答案 3 :(得分:1)
以下是此代码
SELECT isteksikayet.BASVURU_NO AS BasvuruNo, isteksikayet.BASVURU_TARIHI AS BasvuruTarihi, mahalle.ad AS MahalleAdi, konular.ADI AS KonuAdi,
sonucturleri.ADI AS Durum, isteksikayetdetay.GUNCELLEME_TARIHI AS BilgiTarihi, birimler.ad AS BirimAdi
FROM isb_istek_sikayet isteksikayet
INNER JOIN tbl_sistem_mahalle mahalle
ON isteksikayet.MAHALLE_KODU = mahalle.kod
INNER JOIN isb_konular konular
ON isteksikayet.KONU_KODU = konular.KODU
INNER JOIN isb_istek_sikayet_detay isteksikayetdetay
ON isteksikayet.BASVURU_NO = isteksikayetdetay.BASVURU_NO
INNER JOIN isb_sonuc_turleri sonucturleri
ON isteksikayetdetay.SONUC_KODU = sonucturleri.KODU
INNER JOIN mubim_birim birimler
ON isteksikayetdetay.DAIRE_KODU = birimler.kod
ORDER BY BasvuruNo DESC LIMIT 10;
使用
替换代码中的这一行$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$code = "";
for ($i = 0; $i < 6; $i++) {
$code .= $chars[mt_rand(0, strlen($chars)-1)];
}
我希望这会起作用
修改强>
您也可以尝试其他方式
$voucher->code = $code;// it should be dynamic and unique
对于长度约束,试试这个
$code = strtoupper(uniqid()); // if you dont have any restriction on length of code