I am working on an application that has genders as a standardized entity and the gender ids are used in the user entity. So user1 has gender_id = 1.
How do i specify that if the gender id is used elsewhere, you cannot delete this gender?
I have tried searching online but i didn’t find anything that was useful.
public function deleteGender(Gender $gender)
{
$gender->delete();
$this->dispatchBrowserEvent('swal:toast', [
'background' => 'success',
'html' => "The gender <b><i>{$gender->gender_type}</i></b> has been deleted",
]);
}
This is what my current deletion method looks like.
2
Answers
check if gender exist in user or not with help of
exists
method,This is the kind of thing a relational database is specifically built to facilitate. You should not attempt to solve this in PHP, where you will almost certainly introduce errors unless you are very careful in obtaining the correct locks at the correct time.
Instead, you should solve this via an
ON DELETE RESTRICT
(the specific syntax may be different for your database) constraint in the database, which is the only way to guarantee that the database cannot be put into an invalid state.