Reputation: 3289
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');
}
...
Upvotes: 0
Views: 874
Reputation: 642
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');
}
Upvotes: 1