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

LaraSell's avatar

Check Users in roles before remove

I have this function for remove role (spatie package):

public function destroy(Request $request){

    $item_id = $request->get('item_id');
    $item = Role::find($item_id);
    if(empty($item)) {
        return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 404);
    } else {
        $item->delete();

        return response()->json([
            'success' => true,
            'message' => 'Item successfully deleted.',
        ], 200);
    }

}

this code work for me But i need to check role(users in role) before remove it. my mean is remove only role if There is no any user in that role.

0 likes
9 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102
$item = Role::withCount('users')->find($item_id);

Now you can check how many users has the role with $item->users_count

1 like
LaraSell's avatar

@sinnbeck This Work True But this method find Role By users. For ie: if $item_id =='999999999' this code not work and not find true item_id. in action we need first check: role is find? Ok next step check if users in role.

Sinnbeck's avatar

True. But easy to check

try {
    $item = Role::withCount('users')->findOrFail($item_id);
} catch (QueryException) {
    return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 404);
}

if (! $item->users_count) {
    $item->delete();
}
1 like
LaraSell's avatar

@sinnbeck QueryExceptionis good idea. But in my action i see this error:

syntax error, unexpected ')', expecting '|' or variable (T_VARIABLE)

I think Add $e To QueryException.


try {
    $item = Role::withCount('users')->findOrFail($item_id);
} catch (QueryException $e) {
    return response()->json([
            'success' => false,
            'message' => 'Item not found!',
        ], 404);
}

if (! $item->users_count) {
    $item->delete();
}

Sinnbeck's avatar

Oh sorry, yes of course. On a mobile so no code help

LaraSell's avatar

@sinnbeck I check see error:

message: "No query results for model [Spatie\Permission\Models\Role] 999999" exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"

Snapey's avatar

You need to capture NotFoundHttpException not QueryException

Sinnbeck's avatar

Sorry that should have been Illuminate\Database\Eloquent\ModelNotFoundException

The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

sunnycs121's avatar

This is how it can be done:

$role = Role::findOrFail($id);
if(!$role->users) {						
      $role->delete();
}

Please or to participate in this conversation.