5

I created database tables users, groups, and group_user (MySQL).And group_user table (intermediate table) contains the user_id and role_id. users and groups relationship is many to many. I want to delete a group in groups table. Before deleting a group, I want to check if there is any user belongs to that group. I tried to do it this way.

Group.php (Model)

 public function users()
    {
        return $this->belongsToMany('\Modules\User\Models\User');
    }

Service.php

public function deleteGroup($data) {
    if (!isset($data['groupID']))
        return ['error' => 'Failed to delete group. Group id is required'];

    $group = Group::find($data['groupID']);
    if (!$group)
        return ['error' => 'Failed to delete group. Group not found'];

    // check any user belongs to group. 
    $result = $group->users()->pivot->user_id;

    if(!$result){
       $group->delete();
       return ['success' => 'Successfully delete group.'];
    }
    return ['error' => 'Failed to delete group. Group not found'];
}

But this doesn't work.

Iresha Rubasinghe
  • 913
  • 1
  • 10
  • 27
Janaka Pushpakumara
  • 4,769
  • 5
  • 29
  • 34

1 Answers1

3

I find it out.

service.php

public function deleteGroup($data) {

    $group = Group::find($data['groupID']);
    if (!$group){
        return [
            "msg" => "Failed to delete group. Group not found."
        ];
    }
    // find out any one belongs to the group.           
    $result = $group->users->first()->userID;
    if ($result){
        return [
            "msg" => "Failed to delete group. Group has users."
        ];
    }

    $result = $group->delete($data['groupID']);
    if(!$result){
        return [
            "msg" => "Failed to delete group."
        ];
    }

    return [
        "msg" => "Successfully deleted group."
    ];
}

This is how I do it. If there is another way please tell me. Thanks.

Janaka Pushpakumara
  • 4,769
  • 5
  • 29
  • 34
  • 2
    Also you can do like this. $result = $group->users->count(); if ($result>0) { return $this->response(true, $errMsg . 'Group has users'); }else { $group->delete($data['groupID']); return $this->response(false, 'Group deleted successfully'); }' – Janaka Pushpakumara Jan 26 '16 at 03:34