-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathHasComments.php
50 lines (43 loc) · 1.31 KB
/
HasComments.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
<?php
namespace BeyondCode\Comments\Traits;
use BeyondCode\Comments\Contracts\Commentator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
trait HasComments
{
/**
* Return all comments for this model.
*
* @return MorphMany
*/
public function comments()
{
return $this->morphMany(config('comments.comment_class'), 'commentable');
}
/**
* Attach a comment to this model.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function comment(string $comment)
{
return $this->commentAsUser(auth()->user(), $comment);
}
/**
* Attach a comment to this model as a specific user.
*
* @return \Illuminate\Database\Eloquent\Model
*/
public function commentAsUser(?Model $user, string $comment)
{
$commentClass = config('comments.comment_class');
$comment = new $commentClass([
'comment' => $comment,
'is_approved' => ($user instanceof Commentator) ? ! $user->needsCommentApproval($this) : false,
'user_id' => is_null($user) ? null : $user->getKey(),
'commentable_id' => $this->getKey(),
'commentable_type' => get_class($this),
]);
return $this->comments()->save($comment);
}
}