1

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 ?

1 Answers1

2

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())'));
ColinMD
  • 952
  • 6
  • 14
  • Hi Colin, I just understood what you told me hhhh. My goal is to generate for each new line a new UUID, and I wanted to generate it from Str helper . My old version of code (before I remplace it with your answer), it means that Str::uuid() generated a uuid when I executed the migration, and that uuid is the default one in the database, i.e. when I checked the constraints in the 'id' column, I find a default constraint fixed to a string. So, the solution is to generate it form MySQL as you told me, or to generate it from the controller. Thank you again :). – ismail ouzzine Oct 14 '22 at 14:56