Search code examples
phplaraveleloquentlaravel-livewire

How do i add Restriction to deletion of a gender in a eloquent model / livewire component?


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.


Solution

  • 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",
            ]);
         }
    }