Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abbood's avatar

How to add a model with custom auto-increment primary key Laravel

I'm creating a seeder that reads (a subset of) data from our production db into our staging environment.

So I got a model called "categories" which it's primary key is set like so:

                                                             Table "public.categories"
     Column      |              Type              |                        Modifiers                        | 
-----------------+--------------------------------+---------------------------------------------------------+
 id              | integer                        | not null default nextval('categories_id_seq'::regclass) |

since I'm selecting a few categories from my prod db, its ids aren't sequential (they look like this:)

 id
-----
   3
   9
   7
   1
  11
  13
  15
  19
  21
  23
  25
  43
  45
  49
  51
  53
  55
  57
  61

Now I also have a custom seeder file where I would like to create fake categories. Naturally, I'll have to make sure that I'm creating a category whose ID is larger than the category with the highest id. I do that like so:

$factory->define(App\Category::class, function (Faker\Generator $faker) {
    // to avoid duplicating ids
    $lastCategory = Category::select('id')->orderBy('id','desc')->first();

    $category = new Category();
    $category->id  = $lastCategory->id+1;
    $category->ref = str_random(20);
    $category->image = $faker->imageUrl(300, 300);
    $category->priority = rand(0, 100);
    $category->save();

But I keep on getting this error:

[Illuminate\Database\QueryException] SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey" DETAIL: Key (id)=(13) already exists. (SQL: insert into "categories" ("ref_translation", "ref", "parent_id", "top_parent_id", "image", "priority", "updated_at", "created_at") values (translatable.category.ref.HDHCDuNPC4vZoHBB, sandwiches, 124, 124, https://cdn.filepicker.io/api/file/TqB5OvCdSxGDFecrSyrU, 0, 2018-02-20 08:38:20, 2018-02-20 08:38:20) returni ng "id")

[Doctrine\DBAL\Driver\PDOException] SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey" DETAIL: Key (id)=(13) already exists.

although doing the same as a raw postgresql statement works just fine:

insert into categories (id, ref_translation,ref,image,priority) values (200, 'translatable.category.ref.ZAxcHj4hOziemQyz', 'LP2a1bY81IGSza0eHVSqdfsdfdsffds', 'image_name', 1);
INSERT 0 1

How do I get this to work through Laravel's Eloquent ORM?

update

for reference, this is what my class generator looks like:

$factory->define(App\Category::class, function (Faker\Generator $faker) {
    $category = App\Category::create([
        'ref'      => str_random(20),
        'image'    => $faker->imageUrl(300, 300),
        'priority' => rand(0, 100),
    ]);
    $top_parent_id = $category->id;

    return [
        'ref'           => str_random(21),
        'parent_id'     => $top_parent_id,
        'top_parent_id' => $top_parent_id,
        'image'         => $faker->imageUrl(300, 300),
        'priority'      => rand(0, 100),
    ];
});
0 likes
2 replies
lostdreamer_nl's avatar

Confusing, which one is your real category factory? Because you post 2 different versions.

The second one should simply work, as it's not trying to set an ID. is your id field setup to auto-increment ?

abbood's avatar

this fixed it:

        $lastCategory = \App\Category::orderBy('id','desc')->first();
        \DB::statement('alter sequence categories_id_seq restart with '.(intval($lastCategory->id)+1)); 

Please or to participate in this conversation.