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.
$item = Role::withCount('users')->find($item_id);
Now you can check how many users has the role with $item->users_count
@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.
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();
}
@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();
}
Oh sorry, yes of course. On a mobile so no code help
@sinnbeck I check see error:
message: "No query results for model [Spatie\Permission\Models\Role] 999999"
exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
You need to capture NotFoundHttpException not QueryException
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:
This is how it can be done:
$role = Role::findOrFail($id);
if(!$role->users) {
$role->delete();
}
Please sign in or create an account to participate in this conversation.