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

Tushar003's avatar

How to do Error/Exception handling while using Laravel Queries

I m actually writing queries to extract/ update/delete data from database through Laravel. Something like this: private static function delete_user($id) { $deleteUser = User::where('id', '=', $id)->delete(); return true; } I want to do exception handling after the query with proper error code and message if it fails. Can someone help me out?

0 likes
1 reply
ouhare's avatar

Use try, catch !

try {
    $deleteUser = User::whereId($id)->delete();

    // You could use User::destroy($id); .. I guess
    // Be careful, I don't think delete method returns the actual deleted user

} catch (\Illuminate\Database\QueryException $e) {
    // Not sure about namespaces
    // Do things... (check error code for example)
}
1 like

Please or to participate in this conversation.