diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index e064689a8f54..860351b1324c 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -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() @@ -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)); } /** diff --git a/tests/Integration/Database/EloquentWhereHasMorphTest.php b/tests/Integration/Database/EloquentWhereHasMorphTest.php index 15334b5788c2..8661571f959e 100644 --- a/tests/Integration/Database/EloquentWhereHasMorphTest.php +++ b/tests/Integration/Database/EloquentWhereHasMorphTest.php @@ -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