在上篇文章中,我們講到如何邀請其他user進入群組,現在來實現踢人出群組的功能,其實這並不難,怎麼加進來就怎麼踢出去,我們在groups這張table新增user_id以及card_id,就等於加入,那踢出就是刪除罷了。
#從卡片中刪除使用者
public function delete_user(Request $request, $cardId)
{
$userData = $request->userData;
$user = $userData->username;
$deleteUserId = $request->user_id;
$card = $userData->ShowCards->find($cardId);
if (!$card) {
return response()->json(['status' => false, 'error' => 'card search not found'], 400);
}
$cardOwner = $card->create_user;
$cardGroup = $card->ShowGroups;
# 先判斷使用者是否為卡片創立者
if ($user == $cardOwner) {
$Lv = 1;
} else {
$Lv = 2;
}
$delete = $cardGroup->where('users_id', $deleteUserId)->first();
if (!$delete) {
return response()->json(['status' => false, 'error' => 'user search not found'], 400);
}
$deleteUser = Users::find($deleteUserId)->username;
if ($deleteUser == $cardOwner && $Lv == 2) {
return response()->json(['status' => false, 'error' => 'you can not delete card owner'], 400);
}
$delete->delete();
#刪除後若card擁有者不見了,替換下一位card擁有者
$card = Card::find($cardId);
$group = $card->ShowGroups;
if ($deleteUser == $cardOwner) {
if (isset($group[0])) {
$nextOwner = $group->first()->ShowUsers->username;
$card->update(['create_user' => $nextOwner]);
} else {
$card->delete();
}
}
if ($card->ShowUsers->count() == 1) {
$card->update(['private' => true]);
}
return response()->json(['status' => true,]);
}
說明:
code看起來蠻長的,不過是因為有加上之前說的功能,要判斷現在刪的是誰。
這個功能我設計使用者需要輸入user_id和card_id,判斷要在哪張card刪除誰。
以下是刪除後,假設創立者刪了自己
以上是我的踢人功能的作法,這些if判斷式完全是看你的需求,其實也可以做的很簡單,例如只判斷是否為card創立者,只有創立者才能用此功能,這樣或許簡單許多,就看團隊討論這功能細節是如何了,今天就到這邊吧,Bye!