Home > Software design >  Why laravel 7 pivot with sync don't working?
Why laravel 7 pivot with sync don't working?

Time:12-06

This works well.

    if ($request->link) {
        foreach($request->name as $key => $social){
            $stall->socials()->attach($social, ['value' => $request->link[$key] ?? null]);
        }
    }

But it does not work.

    if ($request->link) {
        foreach($request->name as $key => $social){
            $stall->socials()->sync($social, ['value' => $request->link[$key] ?? null]);
        }
    }

Stall.php

public function socials()
{
    return $this->belongsToMany(Social::class)->withPivot('value');
}

The problem is that it does not store in the database at all during the update.

CodePudding user response:

You would need to build your list in a particular way to have set additional fields on the pivot table when syncing. It would be an associative array where the keys are the ids and the value is an associative array where the keys are the fields and the values are the values to set on the pivot fields.

You could use a Collection to create the list in the way you need:

if ($request->link) {
    $stall->socials()->sync(collect($request->name)->mapWithKeys(
        fn ($value, $key) => [$value => ['value' => $request->link[$key] ?? null]]
    ));
}

If you are not using PHP 8 then you could adjust to a regular anonymous function instead of the short arrow syntax:

function ($value, $key) use ($request) { return [$value => ['value' => $request->link[$key] ?? null]]; }

Laravel 7.x Docs - Eloquent - Relationships - Inserting & Updating Related Models - Many To Many Relationships - Syncing Associations sync

Laravel 7.x Docs - Collections - Available Methods mapWithKeys

  • Related