1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CSlant\LaravelLike; |
4
|
|
|
|
5
|
|
|
use CSlant\LaravelLike\Enums\InteractionTypeEnum; |
6
|
|
|
use CSlant\LaravelLike\Models\Like; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\HasMany; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Trait UserInteraction |
12
|
|
|
* use this trait in your User model |
13
|
|
|
* |
14
|
|
|
* @package CSlant\LaravelLike\Traits |
15
|
|
|
* @mixin Model |
16
|
|
|
* @method HasMany<Like, Model> hasMany(string $related, string $foreignKey = null, string $localKey = null) |
17
|
|
|
*/ |
18
|
|
|
trait UserHasInteraction |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Get all likes of the user. This method is used for eager loading. |
22
|
|
|
* |
23
|
|
|
* @return HasMany<self, Model> |
24
|
|
|
*/ |
25
|
|
|
public function likes(): HasMany |
26
|
|
|
{ |
27
|
|
|
$interactionModel = (string) (config('like.interaction_model') ?? Like::class); |
28
|
|
|
$userForeignKey = (string) (config('like.users.foreign_key') ?? 'user_id'); |
29
|
|
|
|
30
|
|
|
return $this->hasMany($interactionModel, $userForeignKey); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Check if the user has liked the given model. |
35
|
|
|
* |
36
|
|
|
* @param string $interactionType |
37
|
|
|
* |
38
|
|
|
* @return static |
39
|
|
|
*/ |
40
|
|
|
public function forgetInteractionsOfType(string $interactionType): static |
41
|
|
|
{ |
42
|
|
|
$this->likes()->where('type', $interactionType)->delete(); |
43
|
|
|
|
44
|
|
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Check if the user has liked the given model. |
49
|
|
|
* |
50
|
|
|
* @param null|string $interactionType |
51
|
|
|
* |
52
|
|
|
* @return static |
53
|
|
|
*/ |
54
|
|
|
public function forgetInteractions(?string $interactionType = null): static |
55
|
|
|
{ |
56
|
|
|
if ($interactionType && in_array($interactionType, InteractionTypeEnum::getValuesAsStrings())) { |
57
|
|
|
return $this->forgetInteractionsOfType($interactionType); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$this->likes()->delete(); |
61
|
|
|
|
62
|
|
|
return $this; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|