feat: add save feature

This commit is contained in:
2026-05-23 01:09:29 +03:30
parent e314f95656
commit 8339a03168
8 changed files with 401 additions and 13 deletions
+59
View File
@@ -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();
}
}