Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GobssRuiz's avatar

I need help refactoring a code, nothing urgent

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
                    ]);
                }
            }
        }
    }
0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@gobssruiz How about this?

if ($request->teams) {
    $teams = collect($data['teams']);

    // Destroy
    DB::table('teams_users')->where('user_id', $id)
        ->whereNotIn('teams_id', $teams)
        ->delete();

    // Add
    foreach ($teams as $teamId) {
        DB::table('teams_users')->updateOrInsert([
            'user_id' => $id,
            'teams_id' => $teamId
        ], [
            'user_id' => $id,
            'teams_id' => $teamId
        ]);
    }
}
2 likes
GobssRuiz's avatar

@tisuchi In the part of adding, isn't it good to check beforehand if it exists, as I did, so as not to run connections with the Bank?

1 like

Please or to participate in this conversation.