Home > Back-end >  Str::uuid() generate same string - Laravel
Str::uuid() generate same string - Laravel

Time:10-09

In my Laravel application, I am trying to use uuid as primary key in my database table, and I am using Str helper to generate a new uuid for each new line.

$table->uuid('id')->primary()->default(Str::uuid());

It works for the first line, but if I try to add another line it generates the same string, so it throw the Integrity constraint violation.

My code in the controller:

public function create(Request $request) {
    $category = new category();
    $category->name = $request->input('name');
    $category->description = $request->input('description');
    $category->save();
    return redirect()->route('categoriesToAdmin');
}

Any solution for that ?

And what do you recommend me to use as PK ; UUID or incremented number ?

CodePudding user response:

What you are actually doing in this code is setting the default UUID to a string UUID, which will be the same on every new line.

What you probably want to do is use MySql's build in UUID function which will work in MySQL8

$table->uuid('id')->primary()->default(DB::raw('(UUID())'));
  • Related