Laravel - Database - Has Many Relationships Using Magic Methods

For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a posts relationship method on the User model:

    
    $user = User::factory()
                ->hasPosts(3)
                ->create();
	

When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models:

    
    $user = User::factory()
                ->hasPosts(3, [
                    'published' => false,
                ])
                ->create();
	

You may provide a closure based state transformation if your state change requires access to the parent model:

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