Is it possible to add pivot data in beforeAttach or attach event

Hi octobercms fans,

Is it possible to add pivot data in beforeAttach or attach event?
Something like this:

$model->bindEvent('model.relation.beforeAttach', function ($relationName, $ids, $attr) use ($model){
  $new_ids = [];
  foreach ($ids as $index => $id) {
       $new_ids[$index]['pivot_data'] = $some_data;
   }
  return $new_ids;
});

As far as I know, its only possible to return true/false to create/not create relation.
Or is there a other way to process data before attaching to belongsToMany relation.

Thanks

Yes you can do more than returning true or false. I think doing it in model.relation.attach would be more appropriate (it should ensure that the relation is already created).

Here is an example

 $model->bindEvent('model.relation.attach', function ($relationName, $ids, $attr) use ($model){
        if ($relationName == 'users') {
            foreach ($ids as $id) {
               $userPivot = $model->users()->where('user_id', $id)->first();
               $userPivot->pivot->workphone_ext = 'some_data';
               $userPivot->pivot->save();
           }
        }
    });
1 Like