Laravel 5.1 - 在保存到数据库时生成唯一的 10 个字母数字字符代码

Laravel 5.1 - Generate a unique 10 alphanumeric character code upon save to database

我在 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]);

}

我知道我可以 $input['uid'] = str_random(10); - 但我如何 确保 它实际上是唯一的,如果不是,则不会重定向回我的表单独一无二?

是否有正确的做法来实现这样的目标?

根据我对您问题的理解,您可以使用模型上的创建事件来实现此目的。这将允许您在模型持久化到数据库之前向模型添加任何内容,而无需任何进一步的交互。

在服务提供商或您的 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.
    });
}

Full documentation for eloquent model events.

这是我以前用过的东西:

  do
  {
      $code = // generate your code
      $gecko_code = Gecko::where('code', $code)->first();
  }
  while(!empty($gecko_code));

创建一个生成 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;
}