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

Galavant's avatar

Pivot table factory seeding

Hey!

I have 3 DB tables with relationships going on. I would like to seed this, but I am unsure how

Users           assigned_users          posts
id      <-----> user_id || post_id  <-----> id

I've made factories for all, but am unsure how to do this. (a post has multiple assigned users, ideally.. but I'll take 1 assigned per post to not over complexify for now )

0 likes
3 replies
s4muel's avatar

if you have a dedicated model for assigned_users (e.g. UserPost), use this approach:

$factory->define(App\UserPost::class, function (Faker $faker) {  
    return [  
        'user_id' => factory(App\User::class)->create()->id,  
        'post_id' => factory(App\Post::class)->create()->id,
    ];
});  

if you don't, use a DB table insert:

DB::table('assigned_users')->insert(
    [
        'user_id' => factory(App\User::class)->create()->id,  
        'post_id' => factory(App\Post::class)->create()->id,
    ]
);

and finally, if you want to use existing users/posts, use a callback

DB::table('assigned_users')->insert(
    [
        'user_id' => function () {  
            return App\User::all()->random()->id;  
        },
        'post_id' => function () {  
            return App\Post::all()->random()->id;  
        },
    ]
);

that should yield some multiple assigned users by chance, or better yet amend the callback as you wish to randomize only couple of them

3 likes
Digitalized's avatar
Level 10

You should set up the relationships first within the model, then reference the relationships in the seeder.

For example if you have a many-to-many relationship between USER and POST, and you are creating posts and users individually, you could just do something like:

$post_1 = Post::create(['title'=>'foo']);
$user_1 = User::create(['first_name'=>'Paul']);

$user_1->posts()->attach($post_1->id);

// or alternatively

$post_1->users()->attach($user_1->id);

On the other hand, if you're using factories, you could do something like this:

$users = factory(User::class, 10)->create()->each(function($user) {
      $user->posts()->attach(factory(Post::class)->create()->id);
});
1 like
phamduchuy552's avatar

I don't know fam, the callback is no longer working in Laravel 8x for me. But it works directly like this: 'user_id' => App\User::all()->random()->id,

Please or to participate in this conversation.