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

waffl's avatar
Level 2

[Solved] Difficulties seeding a User/Post relationship with a uuid?

I am trying to seed a simple User -> Post relationship (using Lumen + Eloquent), where the User has an id of type uuid generated by postgres. It works perfectly with standard, incrementing/integer id values.

[Illuminate\Database\QueryException] SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "user_id" violates not-null constraint

// migration: YYYY_MM_DD_create_users_table.php

...
$table->uuid('id')->default(DB::raw('gen_random_uuid()'));
$table->primary('id');
...
// migration: YYYY_MM_DD_create_posts_table.php
...
$table->uuid('user_id');
$table->foreign('user_id')->references('id')->on('users');
...
// DatabaseSeeder.php
...
factory(App\User::class, 10)->create()->each(function ($u) {
  $u->posts()->save(factory(App\Post::class)->make());
});

However, I am always getting an error, where it is trying to insert a null value for user_id in the posts table.

The eloquent documentation states:

If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false

Which I have done in my model:

// User.php
...
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
  ...
  public $incrementing = false;
  ...
}

Without adjusting the $incrementing value, the seed tries to cast the uuid to an int which clearly doesn't work. However, setting $incrementing to false is simply resulting in a completely null value now.

Any tips/direction would be greatly appreciated.

0 likes
1 reply
waffl's avatar
waffl
OP
Best Answer
Level 2

Ok, I figured it out, and it seems a little clunky but does work. It was just a matter of breaking apart my seeder to create the users first, grab the collection of users, then for each user, create posts.

// DatabaseSeeder.php
...
factory(App\User::class, 10)->create();
$users = App\User::All();

$users->each(function ($u) {
  $u->posts()->saveMany(factory(App\Post::class, 5)->make());
});

Please or to participate in this conversation.