Skip to content

Commit 29d9611

Browse files
committed
Allow WhereHas field to be specified manually
1 parent 75a6360 commit 29d9611

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/Laravel/Filter/WhereHas.php

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,31 @@
1111

1212
class WhereHas extends Filter
1313
{
14+
public Relationship|string|null $field = null;
15+
1416
public static function make(string $name): static
1517
{
1618
return new static($name);
1719
}
1820

21+
public function field(Relationship|string|null $field): static
22+
{
23+
$this->field = $field;
24+
25+
return $this;
26+
}
27+
1928
public function apply(object $query, array|string $value, Context $context): void
2029
{
2130
$value = (array) $value;
22-
$field = $context->fields($context->resource)[$this->name] ?? null;
31+
$field =
32+
$this->field instanceof Relationship
33+
? $this->field
34+
: $context->fields($context->resource)[$this->field ?: $this->name] ?? null;
2335

2436
if (!$field instanceof Relationship || count($field->types) !== 1) {
2537
throw new LogicException(
26-
'The WhereHas filter must have a corresponding non-polymorphic relationship field',
38+
'The WhereHas filter must have a non-polymorphic relationship field',
2739
);
2840
}
2941

@@ -35,9 +47,7 @@ public function apply(object $query, array|string $value, Context $context): voi
3547
$context,
3648
) {
3749
if (array_is_list($value)) {
38-
$query->whereKey(
39-
array_merge(...array_map(fn($v) => explode(',', $v), (array) $value)),
40-
);
50+
$query->whereKey(array_merge(...array_map(fn($v) => explode(',', $v), $value)));
4151
} else {
4252
apply_filters(
4353
$query,

0 commit comments

Comments
 (0)