Along with storing the primary keys of both the related models in the pivot table, you can also store additional data. Imagine we have users and groups in an application. Many users can belong to many groups, but users can also be moderators of groups. To indicate which users are moderators of a group, we can add a is_moderator column on the pivot table. To specify the additional data that should be stored in the pivot table, we can specify a second parameter when calling the attach method:

$user->groups()->attach(1, ['is_moderator' => true]);

We can use the same approach when using the sync method too:

$user->groups()->sync([1 => ['is_moderator' => true]]);
Advertisements