diff --git a/src/Filters/FiltersBelongsTo.php b/src/Filters/FiltersBelongsTo.php index 059924b9..d8d8b22d 100644 --- a/src/Filters/FiltersBelongsTo.php +++ b/src/Filters/FiltersBelongsTo.php @@ -56,7 +56,7 @@ protected function getRelatedModel(Model $modelQuery, string $relationName, stri protected function getRelatedModelFromRelation(Model $model, string $relationName): ?Model { $relationObject = $model->$relationName(); - if (! is_subclass_of($relationObject, Relation::class)) { + if (! $relationObject instanceof Relation) { throw RelationNotFoundException::make($model, $relationName); } diff --git a/tests/FilterTest.php b/tests/FilterTest.php index e7e28c6c..63cacb01 100644 --- a/tests/FilterTest.php +++ b/tests/FilterTest.php @@ -1,14 +1,14 @@ models = TestModel::factory()->count(5)->create(); }); @@ -908,3 +910,24 @@ public function __invoke(Builder $query, $value, string $property): Builder expect($results)->toHaveCount(2); }); + +it('throws RelationNotFoundException when the relation method exists but does not return an Eloquent Relation', function () { + $ModelWithNonRelationMethod = new class () extends TestModel { + protected $table = 'test_models'; + + public function nonRelationMethod() + { + return new stdClass(); + } + }; + + $ModelWithNonRelationMethod::create(['name' => 'test_user']); + + $request = new Request([ + 'filter' => ['author' => '1'], + ]); + + QueryBuilder::for($ModelWithNonRelationMethod::query(), $request) + ->allowedFilters(AllowedFilter::belongsTo('author', 'nonRelationMethod')) + ->get(); +})->throws(RelationNotFoundException::class);