I know it's something non-standard, but I didn't know how to do it.
I'm trying to think how to make a part of my code better, but I can't think of an optimal way.
The idea here is. This part is when the admin edited a user and selected more teams.
This information comes from a select multiple and the data comes as an array.
So I need to delete from the table the teams that he deselected that have the id of this user and add the new teams.
And for both cases I do a foreach.
Do you have any ideas how I can make this part of the code better?
// Teams users table
if ($request->teams) {
$teamsUsers = DB::table('teams_users')->where('user_id', $id)->get();
$teams = collect($data['teams']);
$teamsUserCollect = collect($teamsUsers);
// Teams users table - destroy
if (isset($teamsUsers) && count($teamsUsers) > 0) {
foreach ($teamsUsers as $teamUser) {
if (!$teams->contains($teamUser->teams_id)) {
DB::table('teams_users')->destroy($teamUser->id);
}
}
}
// Teams users table - add
foreach ($teams as $teamId) {
if (!$teamsUserCollect->contains('teams_id', $teamId)) {
DB::table('teams_users')->insert([
'user_id' => $id,
'teams_id' => $teamId
]);
}
}
}
}