mleontenko
5 months ago
509
1
Laravel

Redirect with message if foreign key violated on delete

Posted 5 months ago by mleontenko

If I use delete on a database record that has foreign key associated to it, I get the following error:

SQLSTATE[23503]: Foreign key violation: 7 ERROR: update or delete on table "users" violates foreign key constraint...

The code in controller looks like this:

public function destroy($id)
{
        $user = User::find($id);
        $user->delete();

        return redirect('/admin')->with('success', 'User deleted.');
    }

I'm fine with the above mentioned constraint, but I want to return to a view with an error like this if constraint is violated:

return redirect('/admin')->with('error', 'Cannot delete user with associated records.');

How can I catch the error to return this message?

Please sign in or create an account to participate in this conversation.