Files
opensem/app/Traits/HasComments.php
2021-10-26 21:41:46 +02:00

36 lines
915 B
PHP

<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use App\Contracts\Commentator;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use App\Models\Core\Comment;
trait HasComments
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function comment(string $comment)
{
return $this->commentAsUser(auth()->user(), $comment);
}
public function commentAsUser(?Model $user, string $comment)
{
$comment = new Comment([
'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(),
]);
return $this->comments()->save($comment);
}
}