Level 33
Hi @chron
What about?
$user->bars()->sync([
$bars[$k]->id => ['foo_id' => $foo->id]
]);
Looking at your code it seems you're attempting to sync a single value inside of the loop. Shouldn't you do it outside the loop? You'll end up with a single record attached if you not.
$foo = Foo::where('name', $request['foo'])->first();
$bars = [];
foreach ($request['bars'] as $k => $bar) {
$barId = Bar::firstOrCreate(['name' => $bar])->id;
$bars[$barId] = ['foo_id' => $foo->id];
}
$user->bars()->sync($bars);
1 like