feat: add like table
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
<?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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user