Skip to content

Filterable Trait Fixes #268

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 17, 2025
Merged
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
9 changes: 5 additions & 4 deletions app/Models/Traits/Filterable.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ abstract protected function getFilterableColumns(): array;
* Validate if the column is filterable/sortable.
* @throws InvalidArgumentException
*/
protected function validateColumn(string $column): void
public function validateColumn(string $column): void
{
if (!in_array($column, $this->getFilterableColumns(), true)) {
throw new InvalidArgumentException("Invalid column name: {$column}.");
throw new InvalidArgumentException("Invalid filterable/sortable column name: {$column}.");
}
}

Expand Down Expand Up @@ -55,9 +55,10 @@ public function scopeApplyRelationFilter(
): void {
$query->whereHas($relation, function (Builder $relationQuery) use ($column, $matchMode, $value) {
$related = $relationQuery->getModel();
$fullQualifiedColumnName = $related->getTable() . ".$column";
$relatedClass = get_class($related);
$usedTraits = class_uses_recursive($relatedClass);
$thisTrait = self::class;
$thisTrait = Filterable::class;

if (!in_array($thisTrait, $usedTraits, true)) {
throw new InvalidArgumentException("Related model {$relatedClass} must use the {$thisTrait} trait.");
Expand All @@ -66,7 +67,7 @@ public function scopeApplyRelationFilter(
/** @phpstan-ignore-next-line */
$related->validateColumn($column);
/** @phpstan-ignore-next-line */
$this->applyFilterLogic($relationQuery, $column, $matchMode, $value);
$this->applyFilterLogic($relationQuery, $fullQualifiedColumnName, $matchMode, $value);
});
}

Expand Down