Laravel - Database - Pivot Table Attributes

If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the hasAttached method. This method accepts an array of pivot table attribute names and values as its second argument:

    
    use App\Models\Role;
    use App\Models\User;
    
    $user = User::factory()
                ->hasAttached(
                    Role::factory()->count(3),
                    ['active' => true]
                )
                ->create();
	

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

    
    $user = User::factory()
                ->hasAttached(
                    Role::factory()
                        ->count(3)
                        ->state(function (array $attributes, User $user) {
                            return ['name' => $user->name.' Role'];
                        }),
                    ['active' => true]
                )
                ->create();
	

If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the hasAttached method. In this example, the same three roles will be attached to all three users:

    
    $roles = Role::factory()->count(3)->create();
    
    $user = User::factory()
                ->count(3)
                ->hasAttached($roles, ['active' => true])
                ->create();