Laravel 5.2 生成随机数并保存到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38359833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.2 generate random number and save to database
提问by edmond
I am new to Laravel and I am creating a client table where i have different fields, but also, i have a field called client_number which i want to generate random numbers in laravel and save them to that specific column without a duplicate as well.
我是 Laravel 的新手,我正在创建一个客户端表,其中我有不同的字段,而且,我有一个名为 client_number 的字段,我想在 Laravel 中生成随机数并将它们保存到特定的列中,而不会重复。
Can anyone please help me.
谁能帮帮我吗。
Thanks alot
非常感谢
回答by Kalyan Singh Rathore
Place these three methods into your controller where you are going to handle client registration. In store method you can add more client parameters. You will need to import Client Model in your controller can be done by writing use App\Client;
and also request handler.
将这三个方法放入您要处理客户端注册的控制器中。在 store 方法中,您可以添加更多客户端参数。您需要在控制器中导入客户端模型,可以通过编写use App\Client;
和请求处理程序来完成。
In second method I am checking in table if client number exist or not.
在第二种方法中,我正在检查表中是否存在客户编号。
public function store(Request $request)
{
$client = new Client;
$client->name = $request->name;
$client->client_name = $this->getClientNumber();
$client->save();
}
public function getClientNumber(){
do{
$rand = $this->generateRandomString(6);
}while(!empty(Client::where('client_number',$rand)->first()));
return $rand;
}
public function generateRandomString($length) {
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
回答by Anandan K
You can use str_rand() or rand()predefined functions for get Random Number and check it in DB
您可以使用str_rand() 或 rand()预定义函数来获取随机数并在数据库中检查它
public function store(Request $request)
{
//Generate Random Number
do{
$randomString = str_random(2).rand().str_random(2);
$rand = "CLI_".$randomString;
}while(!empty(clients ::where('client_number',$rand)->first()));
//Insert Query
$Clients = new clients ;
$Clients ->name = $request->name;
$Clients ->client_number = $rand;
$Clients ->save();
}