Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Filters/FiltersBelongsTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
27 changes: 25 additions & 2 deletions tests/FilterTest.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<?php

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\RelationNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Pest\Expectation;

use function PHPUnit\Framework\assertObjectHasProperty;

use Spatie\QueryBuilder\AllowedFilter;

use Spatie\QueryBuilder\Enums\FilterOperator;
use Spatie\QueryBuilder\Exceptions\InvalidFilterQuery;
use Spatie\QueryBuilder\Filters\Filter as CustomFilter;
Expand All @@ -19,6 +19,8 @@
use Spatie\QueryBuilder\Tests\TestClasses\Models\RelatedModel;
use Spatie\QueryBuilder\Tests\TestClasses\Models\TestModel;

use function PHPUnit\Framework\assertObjectHasProperty;

beforeEach(function () {
$this->models = TestModel::factory()->count(5)->create();
});
Expand Down Expand Up @@ -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);