Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole

$types = (array) $types;

$checkMorphNull = $types === ['*']
&& (($operator === '<' && $count >= 1)
|| ($operator === '<=' && $count >= 0)
|| ($operator === '=' && $count === 0)
|| ($operator === '!=' && $count >= 1));

if ($types === ['*']) {
$types = $this->model->newModelQuery()->distinct()->pluck($relation->getMorphType())
->filter()
Expand Down Expand Up @@ -260,7 +266,8 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole
->whereHas($belongsTo, $callback, $operator, $count);
});
}
}, null, null, $boolean);
}, null, null, $boolean)
->when($checkMorphNull, fn (self $query) => $query->orWhereMorphedTo($relation, null));
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/Integration/Database/EloquentWhereHasMorphTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,13 @@ public function testModelScopesAreAccessible()

$this->assertEquals([1, 4], $comments->pluck('id')->all());
}

public function testWhereDoesntHaveMorphWithNullableMorph()
{
$comments = Comment::whereDoesntHaveMorph('commentable', '*')->orderBy('id')->get();

$this->assertEquals([3, 7, 8], $comments->pluck('id')->all());
}
}

class Comment extends Model
Expand Down
Loading