|
2 | 2 |
|
3 | 3 | namespace CSlant\LaravelLike\Traits;
|
4 | 4 |
|
| 5 | +use CSlant\LaravelLike\Enums\InteractionTypeEnum; |
5 | 6 | use CSlant\LaravelLike\Models\Like;
|
6 | 7 | use Illuminate\Database\Eloquent\Model;
|
7 | 8 | use Illuminate\Database\Eloquent\Relations\MorphMany;
|
@@ -37,4 +38,57 @@ public function likes(): MorphMany
|
37 | 38 | {
|
38 | 39 | return $this->morphMany((string) config('like.interaction_model') ?? Like::class, 'model');
|
39 | 40 | }
|
| 41 | + |
| 42 | + /** |
| 43 | + * Check if the model has been interacted by the given user. |
| 44 | + * |
| 45 | + * @param int $userId |
| 46 | + * @param null|InteractionTypeEnum $interactionType |
| 47 | + * |
| 48 | + * @return bool |
| 49 | + */ |
| 50 | + public function isInteractedBy(int $userId, ?InteractionTypeEnum $interactionType = null): bool |
| 51 | + { |
| 52 | + $userForeignKey = (string) (config('like.users.foreign_key') ?? 'user_id'); |
| 53 | + |
| 54 | + $query = $this->likes()->where($userForeignKey, $userId); |
| 55 | + |
| 56 | + if (in_array($interactionType, InteractionTypeEnum::getValuesAsStrings())) { |
| 57 | + $query->where('type', $interactionType); |
| 58 | + } |
| 59 | + |
| 60 | + return $query->exists(); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Check and forget all recorded interactions of the given type. |
| 65 | + * |
| 66 | + * @param string $interactionType |
| 67 | + * |
| 68 | + * @return static |
| 69 | + */ |
| 70 | + public function forgetInteractionsOfType(string $interactionType): static |
| 71 | + { |
| 72 | + $this->likes()->where('type', $interactionType)->delete(); |
| 73 | + |
| 74 | + return $this; |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Check and forget all recorded interactions. |
| 79 | + * |
| 80 | + * @param null|string $interactionType |
| 81 | + * |
| 82 | + * @return static |
| 83 | + */ |
| 84 | + public function forgetInteractions(?string $interactionType = null): static |
| 85 | + { |
| 86 | + if ($interactionType && in_array($interactionType, InteractionTypeEnum::getValuesAsStrings())) { |
| 87 | + return $this->forgetInteractionsOfType($interactionType); |
| 88 | + } |
| 89 | + |
| 90 | + $this->likes()->delete(); |
| 91 | + |
| 92 | + return $this; |
| 93 | + } |
40 | 94 | }
|
0 commit comments