This repository has been archived by the owner on Aug 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Favoriteable.php
82 lines (75 loc) · 1.52 KB
/
Favoriteable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace CodeForms\Repositories\Favorite;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
/**
* @package CodeForms\Repositories\Favorite
*/
trait Favoriteable
{
/**
* @return Illuminate\Database\Eloquent\Model
*/
public static function bootFavoriteable()
{
static::deleted(function (self $model) {
$model->deleteFavorites();
});
}
/**
* @example $post->hasFavorite()
*
* @return boolean
*/
public function hasFavorite(): bool
{
return (bool)$this->favorites()->where('user_id', auth()->user()->id)->count();
}
/**
* @example $post->addFavorite()
*
* @return object|boolean
*/
public function addFavorite()
{
if(!$this->hasFavorite())
return $this->favorites()->create();
return false;
}
/**
* @example $post->unFavorite()
*
* @return mixed
*/
public function unFavorite(): bool
{
if($this->hasFavorite())
return $this->favorites()->where('user_id', auth()->user()->id)->delete();
return false;
}
/**
* @example $post->toggleFavorite()
*
* @return mixed
*/
public function toggleFavorite()
{
return $this->hasFavorite() ? $this->unFavorite() : $this->addFavorite();
}
/**
* @example $post->deleteFavorites()
*
* @return boolean
*/
public function deleteFavorites(): bool
{
return $this->favorites()->delete();
}
/**
* @return Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function favorites()
{
return $this->morphMany(Favorite::class, 'favoriteable');
}
}