Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel sync manytomany error

Tags:

php

laravel

I am attaching user_id, product_id with an extra field. Every thing is working fine until the extra field should be updated. When the field will be filled for second time instead of updating it will add another one to database. and it's obvious because I used attach instead of sync. But when I use sync I get an error.

this is my code:

$price = $request->input('price');
$product = Product::find($id);
$product->users()->attach(Auth::id(), ['price'  => $price]);

and this is the error I get when I use sync:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, integer given

like image 318
Ali Lashini Avatar asked Feb 05 '23 05:02

Ali Lashini


1 Answers

The first parameter of the sync() method should be an array. So correct syntax is:

$product->users()->sync([Auth::id() => ['price' => $price]]);

https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

like image 67
Alexey Mezenin Avatar answered Feb 08 '23 16:02

Alexey Mezenin