Laravel - Database - Belongs To Relationships

Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The for method may be used to define the parent model that factory created models belong to. For example, we can create three App\Models\Post model instances that belong to a single user:

    
    use App\Models\Post;
    use App\Models\User;
    
    $posts = Post::factory()
                ->count(3)
                ->for(User::factory()->state([
                    'name' => 'Jessica Archer',
                ]))
                ->create();
	

If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the for method:

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