Files
opensem/app/Traits/Model/HasComments.php
2024-01-05 01:30:46 +01:00

34 lines
864 B
PHP

<?php
namespace App\Traits\Model;
use App\Contracts\Commentator;
use App\Models\Core\Comment;
use Illuminate\Database\Eloquent\Model;
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);
}
}