mirror of
https://github.com/wearepixel/laravel-comments.git
synced 2026-11-14 14:02:04 +00:00
51 lines
1.3 KiB
PHP
51 lines
1.3 KiB
PHP
<?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);
|
|
}
|
|
}
|