0
votes

I am using voyager admin panel. I am trying to delete permission role, which already assigned to the user, then voyager give me an error:

2020-02-19 11:07:56] local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (data_base_name.users, CONSTRAINT users_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id)) (SQL: delete from roles where id = 4)

voyager should show me a message that role can not delete its assigned to the user.

2
I don't understand the question: You expect an error and this is what you get. What's the problem?Markus Deibel
Doesn't the error message say exactly that? It indicates that the role cannot be deleted as that would violate the constraint on the users table? It is likely that the role_id field on users table cannot be null? Therefore the role cannot be removed as it would require the field to be set to null or it would require the deletion of all users with role_id=4 (also not what you would want I presume)mtholen
@mtholen so it is migration issue, we should need to remove delete cascading from migration?shazim ali
@shazimali I would not be in a position to advise on that as I do not have sufficient information to judge whether you should or shouldn't remove the cascading. That was not the question? An error message comes back which correctly identifies the problem, up to you how to handle that message?mtholen

2 Answers

2
votes
public function destroy(Request $request, $id)
{
    try {
        return parent::destroy($request, $id);
    } catch (QueryException $exception) {
        $message = $exception->getMessage();
        if (strpos($message, 'foreign key constraint') !== false) {
            $message = "This row can't be deleted";
        }

        return back()->with(['message' => $message]);
    }
}
0
votes

You need a try-catch for something like this. Since it's a foreign key assigned to another record then it is expected behaviour not to be able to delete it.

Since you create a message out of the error you should do something like:

try { 
  //query goes here
} catch(\Exception $e){ 
 $error = $e->getMessage();
 return $error;
}