Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ImranKhan's avatar

How to update Many To Many Relationships pivot table

Hi, I am working in laravel 5, created three tables Models, Features and ModelFeatures table. now on update when multiple features try to update if exist else detach the record from pivot table. I have these models..

class Model extends Model { public function hasFeature($feature_id) { foreach($this->features as $feature) { if($feature->pivot->feature_id == $feature_id) return true; }

    return false;
}

public function assignFeature($feature, $options=[])
{
    return $this->features()->attach($feature, $options);
}

public function removeFeature($feature)
{
    return $this->features()->detach($feature);
}

}

class Feature extends Model { public function models() { return $this->belongsToMany('App\Models\MobFeature', 'mob_model_features', 'feature_id', 'model_id'); } }

Now i am trying to update like this, but not working:

public function updateFeatures($request, $id)
{
    $is_success = true;
    $message    = '';

    // get specific model
    $model = Model::find($id);
    
    // check for mobile feature
    if ($request->features) {
        foreach ($request->features as $key => $value) {
            if ( $model->hasFeature($key) ) {
                // what to do next...
            }
            else {
                $model->assignFeature($key, ['feature_val' => $value]);
            }
        }
    }

Update: Thanks, i have update my code now its working. if ($request->features) { $syncFeatures = array(); foreach ($request->features as $key => $value) { if (empty($value)) { continue; }

            if ( !$model->hasFeature($key) ) {
                $model->assignFeature($key, ['feature_val' => $value]);
            }
            else {
                $syncFeatures[$key] = array('feature_val' => $value);
            }
        }
        if (!empty($syncFeatures)) {
            $model->syncFeature($syncFeatures);
        }
    }

and this in model class: public function syncFeature($syncFeatures) { return $this->features()->sync($syncFeatures); } is this the right way ?

0 likes
2 replies
pmall's avatar
pmall
Best Answer
Level 56

You need to use $model->features()->sync([$feature_id => ['pivot_data' => $pivot_value]]);

3 likes
amirhs712's avatar

Tested in laravel 5.6 on a many to many relationship.

$model->pivot->data = $pivot_data; $model->pivot->update();

Please or to participate in this conversation.