Files
opensem/app/Traits/Model/HasComments.php
2024-02-23 08:35:41 +01:00

61 lines
1.7 KiB
PHP

<?php
namespace App\Traits\Model;
use App\Models\Core\Comment;
use App\Repositories\Core\Auth\Users;
use Illuminate\Database\Eloquent\Model;
trait HasComments
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function comment(string $comment)
{
$user = Users::getUser();
return $this->commentAsUser($user, $comment);
}
public function commentAsUser(?Model $user, string $comment)
{
if (trim(strip_tags($comment))) {
$data = new Comment([
'comment' => $comment,
// 'is_approved' => ($user instanceof CanComment) ? ! $user->needsCommentApproval($this) : false,
'is_approved' => true,
'commenter_id' => is_null($user) ? null : $user->getKey(),
'commenter_type' => is_null($user) ? null : $user::class,
'commentable_id' => $this->getKey(),
'commentable_type' => $this::class,
]);
return $this->comments()->save($data);
}
return false;
}
public function commentAsGuest($guest, string $comment)
{
if (trim(strip_tags($comment))) {
$data = new Comment([
'comment' => $comment,
'guest_name' => $guest['name'],
'guest_email' => $guest['email'],
// 'is_approved' => ($guest instanceof CanComment) ? ! $guest->needsCommentApproval($this) : false,
'is_approved' => true,
'commentable_id' => $this->getKey(),
'commentable_type' => $this::class,
]);
return $this->comments()->save($data);
}
return false;
}
}