首页 > 解决方案 > Laravel:将 uuidv4 保存到数据库

问题描述

我正在使用ReactLaravel创建列表。在添加按钮中,我有以下内容

 function handleAdd() {
    const newList = list.concat({ name, id: uuidv4(), value });
    setList(newList);
    setName("");
    setValue("");
  }

const onAddSocial = (e) => {
  e.preventDefault();

const test = {
  value: value,
  name: name,
};

axios.post('http://localhost:8000/api/social', test)
  .then((res) => {
    toast(<div class="text-primary font-weight-bolder">Social link added successfully!</div>,{ delay: 0 });
    console.log(res)
  }).catch((error) => {console.log(error)
  })

}

以及触发创建这两个功能的按钮:

 <Button                  
                onClick={(e) => {
                  props.handleAdd();
                  props.onAddSocial(e);
                }}
              >

该元素已创建,但在数据表中id接收一个递增的值。如何改为传递已创建元素的 uuidv4() ?

商店控制器:

public function store(Request $request)
{
    $data = new Social();
    $data->value = $request->value;
    $data->name = $request->name;
    $data->save();
}

标签: reactjslaravel

解决方案


您必须使用以下代码

在您的社交模型中,您必须像这样使用

public $incrementing = false;

protected $keyType = 'string';


public static function boot(){
    parent::boot();

    static::creating(function ($social) {
        $social->id = Str::uuid(36);
    });
}

在标题部分添加此行

use Illuminate\Support\Str;

在您的数据库\迁移社交文件中添加以下代码

public function up()
{
    Schema::create('socials', function (Blueprint $table) {
        $table->uuid('id', 36)->primary();
        $table->timestamps();
    });
}

推荐阅读