I'm new to Laravel and having problems with ManyToMany relationships.
I have two tables:
A member can belong to many groups, a group can have many members.
I've created the relationships in the models and the pivot table.
When I create a member, I have checkboxes for the groups.
In my store method I do this:
....
$member->save();
if(isset($request->groups)) {
$groups = implode(',', $request->groups);
$member->groups()->sync([$groups]);
}
dd($groups)
gives: "2,7"
I get the error:
QueryException in Connection.php line 761: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'group_id' at row 1 (SQL: insert into
group_member
(group_id
,member_id
) values (2,7, 5))
Where is this 5 coming from and why do I get this error?
Thank you
This error is because of the data type you entered.
Using
implode()
You turn the array into a string while sync() method wants an array as input. Let's try just:
$member->save();
if(isset($request->groups)) {
$member->groups()->sync($request->groups);
}