Showing
2 changed files
with
15 additions
and
14 deletions
| ... | @@ -43,20 +43,21 @@ class Article extends Model | ... | @@ -43,20 +43,21 @@ class Article extends Model |
| 43 | 43 | ||
| 44 | public function getFiltered(array $filters): Collection | 44 | public function getFiltered(array $filters): Collection |
| 45 | { | 45 | { |
| 46 | - return $this->when(array_key_exists('tag', $filters), function ($q) use ($filters) { | 46 | + return $this->filter($filters, 'tag', 'tags', 'name') |
| 47 | - $q->whereRelation('tags', 'name', $filters['tag']); | 47 | + ->filter($filters, 'author', 'user', 'username') |
| 48 | - }) | 48 | + ->filter($filters, 'favorited', 'users', 'username') |
| 49 | - ->when(array_key_exists('author', $filters), function ($q) use ($filters) { | 49 | + ->when(array_key_exists('offset', $filters), function ($q) use ($filters) { |
| 50 | - $q->whereRelation('user', 'username', $filters['author']); | 50 | + $q->offset($filters['offset'])->limit($filters['limit']); |
| 51 | - }) | 51 | + }) |
| 52 | - ->when(array_key_exists('favorited', $filters), function ($q) use ($filters) { | 52 | + ->with('user', 'users', 'tags', 'user.followers') |
| 53 | - $q->whereRelation('users', 'username', $filters['favorited']); | 53 | + ->get(); |
| 54 | - }) | 54 | + } |
| 55 | - ->when(array_key_exists('offset', $filters), function ($q) use ($filters) { | 55 | + |
| 56 | - $q->offset($filters['offset'])->limit($filters['limit']); | 56 | + public function scopeFilter($query, array $filters, string $key, string $relation, string $column) |
| 57 | - }) | 57 | + { |
| 58 | - ->with('user', 'users', 'tags', 'user.followers') | 58 | + return $query->when(array_key_exists($key, $filters), function ($q) use ($filters, $relation, $column, $key) { |
| 59 | - ->get(); | 59 | + $q->whereRelation($relation, $column, $filters[$key]); |
| 60 | + }); | ||
| 60 | } | 61 | } |
| 61 | 62 | ||
| 62 | public function setTitleAttribute(string $title): void | 63 | public function setTitleAttribute(string $title): void | ... | ... |
No preview for this file type
-
Please register or login to post a comment