|
11 | 11 | use Illuminate\Support\Str; |
12 | 12 | use Javaabu\QueryBuilder\Concerns\AppendsAttributesToResults; |
13 | 13 | use Javaabu\QueryBuilder\Exceptions\AllowedAppendsMustBeCalledBeforeAllowedFields; |
| 14 | +use Javaabu\QueryBuilder\Exceptions\AllowedDynamicFieldsMustBeCalledBeforeAllowedFields; |
14 | 15 | use Javaabu\QueryBuilder\Exceptions\FieldsToAlwaysIncludeMustBeCalledBeforeAllowedFields; |
15 | 16 | use Spatie\QueryBuilder\AllowedInclude; |
16 | 17 | use Spatie\QueryBuilder\Exceptions\InvalidFieldQuery; |
@@ -47,6 +48,22 @@ class QueryBuilder extends \Spatie\QueryBuilder\QueryBuilder |
47 | 48 | */ |
48 | 49 | protected $allAppends = null; |
49 | 50 |
|
| 51 | + protected ?Collection $allowedDynamicFields = null; |
| 52 | + |
| 53 | + |
| 54 | + public function allowedDynamicFields($fields): static |
| 55 | + { |
| 56 | + if ($this->allowedFields instanceof Collection) { |
| 57 | + throw new AllowedDynamicFieldsMustBeCalledBeforeAllowedFields(); |
| 58 | + } |
| 59 | + |
| 60 | + $fields = is_array($fields) ? $fields : func_get_args(); |
| 61 | + |
| 62 | + $this->allowedDynamicFields = collect($fields); |
| 63 | + |
| 64 | + return $this; |
| 65 | + } |
| 66 | + |
50 | 67 | /** |
51 | 68 | * Set to ignore invalid filters |
52 | 69 | */ |
@@ -155,7 +172,12 @@ protected function ensureAllFieldsExist(): void |
155 | 172 |
|
156 | 173 | // get rid of any appended fields present |
157 | 174 | $requestedFields = $requestedFields->diff( |
158 | | - $this->prependFieldsWithTableName(($this->allowedAppends ? $this->allowedAppends->all() : []), $modelTable) |
| 175 | + $this->prependFieldsWithTableName(($this->allowedAppends ? $this->allowedAppends->all() : []), $modelTable), |
| 176 | + ); |
| 177 | + |
| 178 | + // get rid of any dynamic fields present |
| 179 | + $requestedFields = $requestedFields->diff( |
| 180 | + $this->prependFieldsWithTableName(($this->allowedDynamicFields ? $this->allowedDynamicFields->all() : []), $modelTable) |
159 | 181 | ); |
160 | 182 |
|
161 | 183 | $unknownFields = $requestedFields->diff($this->allowedFields); |
@@ -294,6 +316,12 @@ protected function addRequestedModelFieldsToQuery(): void |
294 | 316 | $this->prependFieldsWithTableName(($this->allowedAppends ? $this->allowedAppends->all() : []), $modelTableName) |
295 | 317 | ); |
296 | 318 |
|
| 319 | + // get rid of any dynamic fields present |
| 320 | + $prependedFields = array_diff( |
| 321 | + $prependedFields, |
| 322 | + $this->prependFieldsWithTableName(($this->allowedDynamicFields ? $this->allowedDynamicFields->all() : []), $modelTableName) |
| 323 | + ); |
| 324 | + |
297 | 325 | $prependedFields = array_unique($prependedFields); |
298 | 326 |
|
299 | 327 | $this->select($prependedFields); |
|
0 commit comments