feat: add save feature
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
// app/Traits/HasSaves.php
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\SavedItem;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
|
||||
trait HasSaves
|
||||
{
|
||||
public function saves()
|
||||
{
|
||||
return $this->morphMany(SavedItem::class, 'saveable');
|
||||
}
|
||||
|
||||
public function getIsSavedAttribute()
|
||||
{
|
||||
if (!auth()->check()) return false;
|
||||
|
||||
return $this->saves()
|
||||
->where('user_id', auth()->id())
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function getSavedCountAttribute()
|
||||
{
|
||||
return $this->saves()->count();
|
||||
}
|
||||
|
||||
public function toggleSaveStatus()
|
||||
{
|
||||
if ($this->getIsSavedAttribute()) {
|
||||
return $this->removeSave();
|
||||
} else {
|
||||
return $this->addSave();
|
||||
}
|
||||
}
|
||||
|
||||
public function addSave()
|
||||
{
|
||||
if ($this->getIsSavedAttribute()) return false;
|
||||
|
||||
return SavedItem::create([
|
||||
'user_id' => auth()->id(),
|
||||
'saveable_id' => $this->id,
|
||||
'saveable_type' => get_class($this),
|
||||
]);
|
||||
}
|
||||
|
||||
public function removeSave()
|
||||
{
|
||||
if (!$this->getIsSavedAttribute()) return false;
|
||||
|
||||
return SavedItem::where([
|
||||
'user_id' => auth()->id(),
|
||||
'saveable_id' => $this->id,
|
||||
'saveable_type' => get_class($this),
|
||||
])->delete();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user