|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Chrisjk123\Blogger\Traits; |
| 4 | + |
| 5 | +use Chrisjk123\Blogger\Post; |
| 6 | +use Illuminate\Database\Eloquent\Builder; |
| 7 | +use Illuminate\Support\Collection; |
| 8 | + |
| 9 | +trait PostScopes |
| 10 | +{ |
| 11 | + public function scopeWhereCategories(Builder $query, $categories = null) |
| 12 | + { |
| 13 | + $query->with('category'); |
| 14 | + |
| 15 | + if (is_null($categories)) { |
| 16 | + return $query; |
| 17 | + } |
| 18 | + |
| 19 | + if ($categories instanceof Collection) { |
| 20 | + return $query->whereIn( |
| 21 | + 'category_id', |
| 22 | + $categories->pluck('id')->toArray() |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + return $query->where('category_id', $categories->id); |
| 27 | + } |
| 28 | + |
| 29 | + public function scopeWhereCategory(Builder $query, $category, $type = 'slug') |
| 30 | + { |
| 31 | + $query->with('category'); |
| 32 | + |
| 33 | + return $query->whereHas('category', function (Builder $query) use ($type, $category) { |
| 34 | + return $query->where($type, $category); |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + public function scopeRelatedByPostTags(Builder $query, Post $post) |
| 39 | + { |
| 40 | + return $query->whereHas('tags', function (Builder $query) use ($post) { |
| 41 | + return $query->whereIn('name', $post->tags->pluck('name')); |
| 42 | + })->where('id', '!=', $post->id); |
| 43 | + } |
| 44 | + |
| 45 | + public function scopeRelatedByPostCategory(Builder $query, Post $post) |
| 46 | + { |
| 47 | + return $query->whereHas('category', function (Builder $query) use ($post) { |
| 48 | + return $query->where('id', $post->category->id); |
| 49 | + })->where('id', '!=', $post->id); |
| 50 | + } |
| 51 | + |
| 52 | + public function scopeIsPublished(Builder $query) |
| 53 | + { |
| 54 | + return $query->where('status', self::PUBLISHED) |
| 55 | + ->whereNotNull('published_at'); |
| 56 | + } |
| 57 | + |
| 58 | + public function scopeIsNotPublished(Builder $query) |
| 59 | + { |
| 60 | + return $query->whereIn('status', [ |
| 61 | + self::DRAFT, |
| 62 | + self::SCHEDULED, |
| 63 | + ])->whereNull('published_at'); |
| 64 | + } |
| 65 | +} |
0 commit comments