-
Notifications
You must be signed in to change notification settings - Fork 51
/
HasTags.php
60 lines (50 loc) · 1.25 KB
/
HasTags.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
<?php
namespace App\Traits;
use App\Models\Tag;
trait HasTags
{
/**
* Get all of the tags for the model.
*/
public function tags()
{
return $this->morphToMany(Tag::class, 'model', 'model_has_tags')->withTimestamps();
}
public function scopeFilterByTags($query, $tags)
{
if (is_array($tags)) {
return $query->whereHas('tags', function ($subQuery) use ($tags) {
$subQuery->whereIn('tag_id', $tags);
});
}
if (is_string($tags)) {
return $query->whereHas('tags', function ($subQuery) use ($tags) {
$subQuery->where('tag_id', $tags);
});
}
}
public function untag($slug)
{
$this->tag($slug, false);
}
public function tag($slug, $status = true)
{
$tag = Tag::slug($slug)->first();
if (! $tag) {
return;
}
if ($status) {
$this->tags()->syncWithoutDetaching($tag);
return;
}
$this->tags()->detach($tag);
}
public function hasTag(string $slug)
{
$tag = Tag::slug($slug)->first();
if ($tag) {
return $this->tags->contains($tag);
}
return false;
}
}