Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Str::uuid() generate same string – Laravel

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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())'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading