diff --git a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php index c443e7313b06..81020f6817cc 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php @@ -275,7 +275,7 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole $type = Relation::getMorphedModel($type) ?? $type; } - return $this->where(function ($query) use ($relation, $callback, $operator, $count, $types) { + return $this->where(function ($query) use ($relation, $callback, $operator, $count, $types, $checkMorphNull) { foreach ($types as $type) { $query->orWhere(function ($query) use ($relation, $callback, $operator, $count, $type) { $belongsTo = $this->getBelongsToRelation($relation, $type); @@ -290,8 +290,9 @@ public function hasMorph($relation, $types, $operator = '>=', $count = 1, $boole ->whereHas($belongsTo, $callback, $operator, $count); }); } - }, null, null, $boolean) - ->when($checkMorphNull, fn (self $query) => $query->orWhereMorphedTo($relation, null)); + + $query->when($checkMorphNull, fn (self $query) => $query->orWhereMorphedTo($relation, null)); + }, null, null, $boolean); } /** diff --git a/tests/Integration/Database/EloquentWhereHasMorphTest.php b/tests/Integration/Database/EloquentWhereHasMorphTest.php index 8661571f959e..c551b08128ca 100644 --- a/tests/Integration/Database/EloquentWhereHasMorphTest.php +++ b/tests/Integration/Database/EloquentWhereHasMorphTest.php @@ -27,6 +27,7 @@ protected function afterRefreshingDatabase() Schema::create('comments', function (Blueprint $table) { $table->increments('id'); + $table->string('title'); $table->nullableMorphs('commentable'); $table->softDeletes(); }); @@ -45,7 +46,10 @@ protected function afterRefreshingDatabase() $models[] = null; // deleted foreach ($models as $model) { - (new Comment)->commentable()->associate($model)->save(); + $comment = new Comment(); + $comment->commentable()->associate($model); + $comment->title = 'foo'; + $comment->save(); } } @@ -262,6 +266,22 @@ public function testWhereDoesntHaveMorphWithNullableMorph() $this->assertEquals([3, 7, 8], $comments->pluck('id')->all()); } + + public function testWhereDoesntHaveMorphWithNullableMorphAndAdditionalWhereIsLogicallyGrouped() + { + $commentsWhereFirst = Comment::whereNot('title', 'foo') + ->whereDoesntHaveMorph('commentable', '*') + ->orderBy('id') + ->get(); + + $commentsWhereLast = Comment::whereDoesntHaveMorph('commentable', '*') + ->whereNot('title', 'foo') + ->orderBy('id') + ->get(); + + $this->assertCount(0, $commentsWhereFirst); + $this->assertCount(0, $commentsWhereLast); + } } class Comment extends Model