Skip to content
Advertisement

Laravel eloquent multiple belongsTo seeding

I have three models, User, Category and Article.

Article belongs to both a User and a Category where the foreign keys user_id and category_id are not null.

Am lost trying to seed the database with fake data via factories accordingly, here’s the seeding code…

// 2 categories and 12 articles, 6 per category
// TODO: A user should have 6 articles with mixed categories 
// 3 from each category
// So we will have 2 users
factory(Category::class, 2)->create()->each(function($category) {
    factory(User::class)->create()->each(function($user) use ($category) {
        // How to assign an Article to $category or $user while creating?
        $user->articles()->createMany(
                    factory(Article::class, 3)->make()->toArray()
                ); // category_id can't be null
        // OR
        $category->articles()->createMany(
                    factory(Article::class, 3)->make()->toArray()
                ); // user_id can't be null
    });
});

I’ll get one of two errors, either

Column user_id doesn’t have a default value

Or

Column category_id doesn’t have a default value

Which is logical due to the Article table migration

$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

How can I pass the category_id or user_id to the factory call?
Is there a better way to acheive this?

Thanks in advance

Advertisement

Answer

You can override attributes for your factory by passing an array with the desired attributes to the make() method:

Change

$user->articles()->createMany(
  factory(Article::class, 3)->make()->toArray()
);

to

$user->articles()->createMany(
  factory(Article::class, 3)->make([
    'category_id' => $category->id
  ])->toArray()
);

to override the category_id attribute.

https://laravel.com/docs/6.x/database-testing#using-factories

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement