When I want to delete a row from table I want to check the tables which use the id of this row. If used then it doesn't allow to delete.
Asked
Active
Viewed 155 times
2
-
How you consider id in used? You mean it available in other table? Please give some more details. – tejash patel Oct 23 '18 at 04:38
-
I believe that's called [referential integrity](https://www.google.com/search?q=database+id+referential+integrity). Also see [Maintaining Referential Integrity - Good or Bad?](https://stackoverflow.com/q/5794417/608639) and [Laravel check for constraint violation](https://stackoverflow.com/q/26363271/608639) – jww Oct 23 '18 at 06:09
2 Answers
0
You can simply check whether specific column(containing other table's key) in the row is empty or null and if it is empty then delete the row otherwise skip it. You have two ways in which you can do it-
- using eloquent get the row by primary key and check the property on collection.
- write a stored procedure in the database and call it in your Laravel code.

Chirag Chaudhari
- 1,617
- 3
- 14
- 20
0
You can use the deleting
model event to check if the relationships exist. If they do, then prevent the delete.
https://laravel.com/docs/5.7/eloquent#events
If you create an observer for your model, you can use something like this:
public function deleting($model)
{
if($model->someRelation->count()) { // replace ->someRelation with whatever you want to check
return false; // prevent delete
}
if($model->anotherRelation->count()) {
return false; // prevent delete
}
}

newUserName02
- 1,598
- 12
- 17