Laravel 8 - Factories & Foreign Keys

4.5k Views Asked by At

I haven't been able to locate how to manage foreign keys when creating Factories and Seeders.

I have a users table and a blog_posts table. The blog_posts table has a foreign key user_id that references users.id. I would like to seed my database with users and blog posts.

I have seen how to create a new user for each seeded blog post with the following:

/**
 * Define the BlogPost model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::factory(),
        'created_at' => now(),
        'updated_at' => now(),
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(6, true)
    ];
}

...but I would like to reference existing users since I am performing the database seed like so:

/**
 * Seed the application's database.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UsersTableSeeder::class, 
        BlogPostsTableSeeder::class
    ]);
}
2

There are 2 best solutions below

0
On BEST ANSWER

We can retrieve a random existing User and assign it in the BlogPost Factory as follows:

/**
 * Define the BlogPost model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::inRandomOrder()->first()->id,
        'created_at' => now(),
        'updated_at' => now(),
        'title' => $this->faker->words(5, true),
        'body' => $this->faker->paragraphs(6, true)
    ];
}

2
On

Assuming your User model has a hasMany relationship called blogPosts, you could do the following:

User::factory()
    ->hasBlogPosts(6)
    ->create();

This would create your User and 6 associated BlogPosts.