Laravel - Database - Has Many Relationships

Next, let's explore building Eloquent model relationships using Laravel's fluent factory methods. First, let's assume our application has an App\Models\User model and an App\Models\Post model. Also, let's assume that the User model defines a hasMany relationship with Post. We can create a user that has three posts using the has method provided by the Laravel's factories. The has method accepts a factory instance:

    
    use App\Models\Post;
    use App\Models\User;
    
    $user = User::factory()
                ->has(Post::factory()->count(3))
                ->create();
	

By convention, when passing a Post model to the has method, Laravel will assume that the User model must have a posts method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate:

    
    $user = User::factory()
                ->has(Post::factory()->count(3), 'posts')
                ->create();
	

Of course, you may perform state manipulations on the related models. In addition, you may pass a closure based state transformation if your state change requires access to the parent model:

    
    $user = User::factory()
                ->has(
                    Post::factory()
                            ->count(3)
                            ->state(function (array $attributes, User $user) {
                                return ['user_type' => $user->type];
                            })
                )
                ->create();