This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Followable.php
101 lines (88 loc) · 2.27 KB
/
Followable.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace App\RealWorld\Follow;
use App\User;
trait Followable
{
/**
* Check if the authenticated user is following this user.
*
* @return bool
*/
public function getFollowingAttribute()
{
if (! auth()->check()) {
return false;
}
if (! $this->relationLoaded('followers')) {
$this->load(['followers' => function ($query) {
$query->where('follower_id', auth()->id());
}]);
}
$followers = $this->getRelation('followers');
if (! empty($followers) && $followers->contains('id', auth()->id())) {
return true;
}
return false;
}
/**
* Follow the given user.
*
* @param User $user
* @return mixed
*/
public function follow(User $user)
{
if (! $this->isFollowing($user) && $this->id != $user->id)
{
return $this->following()->attach($user);
}
}
/**
* Unfollow the given user.
*
* @param User $user
* @return mixed
*/
public function unFollow(User $user)
{
return $this->following()->detach($user);
}
/**
* Get all the users that this user is following.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function following()
{
return $this->belongsToMany(User::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}
/**
* Get all the users that are following this user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followers()
{
return $this->belongsToMany(User::class, 'follows', 'followed_id', 'follower_id')->withTimestamps();
}
/**
* Check if a given user is following this user.
*
* @param User $user
* @return bool
*/
public function isFollowing(User $user)
{
return !! $this->following()->where('followed_id', $user->id)->count();
}
/**
* Check if a given user is being followed by this user.
*
* @param User $user
* @return bool
*/
public function isFollowedBy(User $user)
{
return !! $this->followers()->where('follower_id', $user->id)->count();
}
}