67 lines
1.5 KiB
PHP
67 lines
1.5 KiB
PHP
<?php
|
|
// app/Traits/HasComments.php
|
|
namespace App\Traits;
|
|
|
|
use App\Models\Comment;
|
|
|
|
trait HasComments
|
|
{
|
|
public function comments()
|
|
{
|
|
return $this->morphMany(Comment::class, 'commentable');
|
|
}
|
|
// Get user's specific comment
|
|
public function userComment()
|
|
{
|
|
if (!auth()->check()) return null;
|
|
|
|
return $this->comments()
|
|
->where('user_id', auth()->id())
|
|
->first();
|
|
}
|
|
|
|
// Check if user has commented
|
|
public function getHasUserCommentedAttribute()
|
|
{
|
|
return !is_null($this->userComment());
|
|
}
|
|
|
|
// Get user's comment content
|
|
public function getUserCommentAttribute()
|
|
{
|
|
$comment = $this->userComment();
|
|
return $comment ? $comment->content : null;
|
|
}
|
|
|
|
// Get user's comment id
|
|
public function getUserCommentIdAttribute()
|
|
{
|
|
$comment = $this->userComment();
|
|
return $comment ? $comment->id : null;
|
|
}
|
|
|
|
// Get latest comments with user info
|
|
public function getLatestCommentsAttribute()
|
|
{
|
|
return $this->comments()
|
|
->with('user')
|
|
->latest()
|
|
->limit(10)
|
|
->get();
|
|
}
|
|
|
|
// Get paginated comments
|
|
public function getPaginatedComments($perPage = 15)
|
|
{
|
|
return $this->comments()
|
|
->with('user')
|
|
->latest()
|
|
->paginate($perPage);
|
|
}
|
|
|
|
|
|
public function getCommentsCountAttribute()
|
|
{
|
|
return $this->comments()->count();
|
|
}
|
|
} |