59 lines
1.3 KiB
PHP
59 lines
1.3 KiB
PHP
<?php
|
|
// app/Traits/HasLikes.php
|
|
namespace App\Traits;
|
|
|
|
use App\Models\Like;
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
|
|
trait HasLikes
|
|
{
|
|
public function likes(): MorphMany
|
|
{
|
|
return $this->morphMany(Like::class, 'likeable');
|
|
}
|
|
|
|
public function getIsLikedAttribute()
|
|
{
|
|
if (!auth()->check()) return false;
|
|
|
|
return $this->likes()
|
|
->where('user_id', auth()->id())
|
|
->exists();
|
|
}
|
|
|
|
public function getLikesCountAttribute()
|
|
{
|
|
return $this->likes()->count();
|
|
}
|
|
|
|
public function toggleLike()
|
|
{
|
|
if ($this->getIsLikedAttribute()) {
|
|
return $this->removeLike();
|
|
} else {
|
|
return $this->addLike();
|
|
}
|
|
}
|
|
|
|
public function addLike()
|
|
{
|
|
if ($this->getIsLikedAttribute()) return false;
|
|
|
|
return Like::create([
|
|
'user_id' => auth()->id(),
|
|
'likeable_id' => $this->id,
|
|
'likeable_type' => get_class($this),
|
|
]);
|
|
}
|
|
|
|
public function removeLike()
|
|
{
|
|
if (!$this->getIsLikedAttribute()) return false;
|
|
|
|
return Like::where([
|
|
'user_id' => auth()->id(),
|
|
'likeable_id' => $this->id,
|
|
'likeable_type' => get_class($this),
|
|
])->delete();
|
|
}
|
|
} |