src/Traits/WorksWithRelations.php
protected function updateOrCreateBelongsToMany(array $fillable, Model $model, Relation $relation)
    {
        $keys = [];
        $records = [];

        $related = $relation->getRelated();

        foreach ($fillable as $fields) {
            if (array_key_exists('id', $fields)) {
                $id = $fields['id'];
                array_push($keys, $id);
            } else {
                $id = '';
            }

            if (array_except($fields, ['id'])) {
                $record = $related->updateOrCreate(['id' => $id], $fields);
                array_push($keys, $record->id);
                array_push($records, $record);
            }
        }

        $relation->sync($keys);

        return $records;
    }
protected function updateOrCreateBelongsToMany(array $fillable, Model $model, Relation $relation)
    {
        $keys = [];
        $records = [];

        $related = $relation->getRelated();

        foreach ($fillable as $fields) {
            if (array_key_exists('id', $fields)) {
                $id = $fields['id'];
                array_push($keys, $id);
            } else {
                $id = '';
            }

            if (array_except($fields, ['id'])) {
                $record = $related->updateOrCreate(['id' => $id], $fields);
                array_push($keys, $record->id);
                array_push($records, $record);
            }
        }

        $relation->sync($keys);

        return $records;
    }
protected function updateOrCreateBelongsToMany ( array $ fillable , Model $ model , Relation $ relation ) { $ keys = [ ] ; $ records = [ ] ; $ related = $ relation -> getRelated ( ) ; foreach ( $ fillable as $ fields ) { if ( array_key_exists ( 'id' , $ fields ) ) { $ id = $ fields [ 'id' ] ; array_push ( $ keys , $ id ) ; } else { $ id = '' ; } if ( array_except ( $ fields , [ 'id' ] ) ) { $ record = $ related -> updateOrCreate ( [ 'id' => $ id ] , $ fields ) ; array_push ( $ keys , $ record -> id ) ; array_push ( $ records , $ record ) ; } } $ relation -> sync ( $ keys ) ; return $ records ; }
BelongsToMany relation updateOrCreate logic.

@param array    $fillable The relation fillable.
@param Model    $model    The eloquent model.
@param Relation $relation The eloquent relation.

@return array
BelongsToMany relation updateOrCreate logic .