User.php
1.79 KB
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
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory;
protected $fillable = ['username', 'email', 'password', 'bio', 'images'];
protected $visible = ['username', 'email', 'bio', 'images'];
public function getRouteKeyName(): string
{
return 'username';
}
public function articles(): HasMany
{
return $this->hasMany(Article::class);
}
public function favoritedArticles(): BelongsToMany
{
return $this->belongsToMany(Article::class);
}
public function followers(): BelongsToMany
{
return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}
public function following(): BelongsToMany
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}
public function doesUserFollowAnotherUser(int $followerId, int $followingId): bool
{
return $this->where('id', $followerId)->whereRelation('following', 'id', $followingId)->exists();
}
public function doesUserFollowArticle(int $userId, int $articleId): bool
{
return $this->where('id', $userId)->whereRelation('favoritedArticles', 'id', $articleId)->exists();
}
public function setPasswordAttribute(string $password): void
{
$this->attributes['password'] = bcrypt($password);
}
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}