Laravel - 无法在多对多关系中找到()附加对象

in my POST form users are able to add other users to a room. I put a unique constraint on the link (no duplicate entry in the link between users and rooms). However when I refresh my page (f5) after submitting the form, Laravel complains about duplicate entries, although I do check if the objects are attached before.

Here's the code:

$roomUsers = Room::find($request->room_id)->users();

if ($request->add != null) {
    foreach ($request->add as $uId)
        // if null, user hasnt been attach yet
        if (!$roomUsers->find($uId)) {
            Log::debug($roomUsers->find($uId) == null ? 'null' : 'not null');
            // then we can attach him
            $roomUsers->attach($uId);
        }
}

The line !$roomUsers->find($uId) returns true yet the object has been attached in the previous iteration. How is that possible ? Thanks

The reason you're above code isn't working is because you're not creating a new instance of BelongsToMany for each check. This means that every time you call find you're not actually creating a new query you're just adding to the existing one e.g.

say you the ids to add are [1, 2, 3] by the last check your query would effectively be:

SELECT * FROM users WHERE id = 1 AND id = 2 AND id = 3

To keep with the above logic you could do:

$room = Room::find($request->room_id);

if ($request->add != null) {
    foreach ($request->add as $uId)
        // if null, user hasnt been attach yet
        if (!$room->users()->find($uId)) {
            // then we can attach him
            $room->users()->attach($uId);
        }
}

Or a much simpler way to go about this would be to syncWithoutDetaching.

Your code could then look something like:

$roomUsers = Room::find($request->room_id);

if ($request->has('add')) {
    $roomUsers->users()->syncWithoutDetaching($request->add);
}

Hope this helps!