0
votes

In my project I have two tables (category and product) which are connected in relationship. When I try delete category which is assigned to the product, Laravel returned:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (magazyn.products, CONSTRAINT products_article_id_foreign FOREIGN KEY (article_id) REFERENCES articles (id)) (SQL: delete from articles where id = 23)

I know why laravel returns this error but I have a question: How do I create an information example: "You cannot delete this category, because it contains products"

1

1 Answers

2
votes

Errors in your query when done via Eloquent should return a QueryException object. As such, you can catch it and then parse it to show a message. Of course, that second part is the hard part because there are so many variations of errors, but you might be able to detect common query issues.

For example:

try {
    // Run query that might fail here
} catch(QueryException $e) {
   if (stristr($e->getMessage(), 'Integrity constraint violation') {
       return 'Record cannot be deleted or updated because it has related entities!';
   }
}

You should know the context of the original query (whether it is an update or delete), so you can probably refine the error message based on that information as well.