Using factory with nested relationships in Laravel 8

  eloquent, factory, laravel, laravel-8

My models are User, Post and Category.

I’m trying to use factories to seed all the data.
The first level (Users with posts) work fine by doing

// Create random users
User::factory()
    ->times(10)
    ->hasPosts(10)
    ->hasCategories(1)
    ->create();

But I want each post to have a category.
I’ve tried to do this (based on this article):

User::factory()
    ->times(10)
    ->has(
        PostFactory::times(5)
            ->hasCategories(1)
            ->create()
    )
    ->hasCategories(1)
    ->create();

But throws this error:

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`description`, `updated_at`, `created_at`) values (odio facilis molestiae, 2020-11-29 21:22:50, 2020-11-29 21:22:50))

Source: Laravel

Leave a Reply