Skip to content
Advertisement

Check if hasMany Relationship Exists in Laravel 8 Before Deleting Record

I am trying to check if a relationship exists prior to deleting it. I’ve seen many other posts online about this, but can’t seem to make it work–when I hit delete it ignores my @if statement and deletes the record.

Models/Workorder.php

...
public function continuations()
    {
        return $this->hasMany(Continuation::class);
    }
...

Models/Continuation.php

...
public function workorder()
    {
        return $this->belongsTo(Workorder::class, 'workorder_id');
    }
...

workorders/index.blade.php

...
  <td class="pr-6">
        <a wire:click="deleteWorkorder({{$workorder->id}})"
           role="menuitem">
        </a>
  </td>
...

Workorders/Index.php

...
public function deleteWorkorder($id)
    {
        $record = Workorder::find($id);
        $conExists = Continuation::where('workorder_id', $record->id)->exists();

        if($conExists){
            session()->flash('failed-message', 'You can't delete a workorder that has a Continuation');
            return;
        }
        $record->delete();
        session()->flash('success-message', 'Workorder Deleted Successfully');

    }
...

Advertisement

Answer

Try something like that by using isNotEmpty()

$workorder= workorder::find($request->id);
            if ($workorder->continuations->isNotEmpty()) {
                return session()->flash('failed-message', 'You can't delete a workorder that has a Continuation');
            }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement