Search code examples
laraveldestroy

Why is my exception not caught by the Laravel destroy method?


Why is my exception not caught?

    try {
        \Account::destroy($id);
        return Redirect::to("/manager/account")
                            ->with("success_message", "Item excluido com sucesso");
    } catch (Exception $e) {
        return Redirect::to("/manager/account/{$id}/edit")
                        ->with("error_message", "Erro ao excluir item");
    }

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (imob_io.users, CONSTRAINT users_account_id_foreign FOREIGN KEY (account_id) REFERENCES accounts (id)) (SQL: delete from accounts where id = 2)


Solution

  • Currently you are catching the class Exception inside your current namespace. Instead you should refer to the global type \Exception:

    catch (\Exception $e){
        return Redirect::to("/manager/account/{$id}/edit")
                        ->with("error_message", "Erro ao excluir item");
    }
    

    I also recommend you narrow it down a bit instead of just catching every exception. For example you could catch QueryException which will be thrown for constraint violations etc.

    catch(\Illuminate\Database\QueryException $e)