Laravel 5.1 - 保存到数据库时生成唯一的 10 个字母数字字符代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35083940/
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.1 - Generate a unique 10 alphanumeric character code upon save to database
提问by Andy Holmes
I'm working in Laravel 5.1 and saving a gecko to a database. My code for my store
method is below:
我在 Laravel 5.1 中工作并将壁虎保存到数据库中。我的store
方法代码如下:
public function store(GeckoRequest $request)
{
$user_id = Auth::user()->id;
$input = $request->all();
$input['genetics'] = json_encode($input['genetics'], JSON_FORCE_OBJECT);
$input['user_id'] = $user_id;
Gecko::create($input);
$name = str_replace(' ', '-', $request['name']);
flash()->success('Success!', 'Your gecko has been added to the system');
return redirect()->action('GeckoController@show', [$name]);
}
I know I could do $input['uid'] = str_random(10);
- But how do I ensureit is in fact unique and won't redirect back to my form if it isn't unique?
我知道我可以做$input['uid'] = str_random(10);
- 但是我如何确保它实际上是独一无二的,并且如果它不是独一无二的,则不会重定向回我的表单?
Is there a proper practice into achieving something like this?
是否有适当的做法来实现这样的目标?
回答by Mike Miller
Create a function that generates the 10 digit random key then passes it through a validator with a unique rule set. If the validator gives you an error re-run the same function to generate a new one
创建一个生成 10 位随机密钥的函数,然后将其通过具有唯一规则集的验证器。如果验证器给你一个错误重新运行相同的函数来生成一个新的
public function randomId(){
$id = str_random(10);
$validator = \Validator::make(['id'=>$id],['id'=>'unique:table,col']);
if($validator->fails()){
return $this->randomId();
}
return $id;
}
回答by user2094178
Here is something I've used before:
这是我以前使用过的东西:
do
{
$code = // generate your code
$gecko_code = Gecko::where('code', $code)->first();
}
while(!empty($gecko_code));
回答by David Barker
From what I understand of your question, you could achieve this using a created event on the model. This will allow you to add anything to the model before it is persisted in the database without any further interaction required.
根据我对您的问题的理解,您可以使用模型上的 created 事件来实现这一点。这将允许您在将任何内容持久化到数据库中之前向模型添加任何内容,而无需任何进一步的交互。
In a service provider, or your App\Providers\AppServiceProvider
add the event to the boot method.
在服务提供者中,或者您App\Providers\AppServiceProvider
将事件添加到引导方法中。
public function boot()
{
User::creating(function ($user) {
// When ever a User model is created
// this event callback will be fired.
$user->setAttribute('randomString', str_random(10));
// Returning 'false' here will stop the
// creation of the model.
});
}