skip to Main Content

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


  1. check if gender exist in user or not with help of exists method,

    public function deleteGender(Gender $gender)
    {
        $isGenderExists = User::where("gender_id",$gender->id)->exists();
        if($isGenderExists){
            $this->dispatchBrowserEvent('swal:toast', [
                'background' => 'error',
                'html' => "your restriction message goes here....",
            ]);
        }else{
            $gender->delete();
            $this->dispatchBrowserEvent('swal:toast', [
                'background' => 'success',
                'html' => "The gender <b><i>{$gender->gender_type}</i></b> has been deleted",
            ]);
         }
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search