fix
This commit is contained in:
+22
-14
@@ -3,7 +3,6 @@
|
|||||||
namespace App\Traits;
|
namespace App\Traits;
|
||||||
|
|
||||||
use App\Models\SavedItem;
|
use App\Models\SavedItem;
|
||||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
||||||
|
|
||||||
trait HasSaves
|
trait HasSaves
|
||||||
{
|
{
|
||||||
@@ -14,11 +13,7 @@ public function saves()
|
|||||||
|
|
||||||
public function getIsSavedAttribute()
|
public function getIsSavedAttribute()
|
||||||
{
|
{
|
||||||
if (!auth()->check()) return false;
|
return $this->isSavedByAuthUser();
|
||||||
|
|
||||||
return $this->saves()
|
|
||||||
->where('user_id', auth()->id())
|
|
||||||
->exists();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getSavedCountAttribute()
|
public function getSavedCountAttribute()
|
||||||
@@ -26,20 +21,31 @@ public function getSavedCountAttribute()
|
|||||||
return $this->saves()->count();
|
return $this->saves()->count();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check the saves() relation directly (not the is_saved attribute, which a
|
||||||
|
// model may override to point at a different table — e.g. Media), so toggle
|
||||||
|
// always decides against the same table it writes to.
|
||||||
|
protected function isSavedByAuthUser(): bool
|
||||||
|
{
|
||||||
|
if (!auth()->check()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->saves()->where('user_id', auth()->id())->exists();
|
||||||
|
}
|
||||||
|
|
||||||
public function toggleSaveStatus()
|
public function toggleSaveStatus()
|
||||||
{
|
{
|
||||||
if ($this->getIsSavedAttribute()) {
|
return $this->isSavedByAuthUser() ? $this->removeSave() : $this->addSave();
|
||||||
return $this->removeSave();
|
|
||||||
} else {
|
|
||||||
return $this->addSave();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function addSave()
|
public function addSave()
|
||||||
{
|
{
|
||||||
if ($this->getIsSavedAttribute()) return false;
|
if (!auth()->check()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return SavedItem::create([
|
// Idempotent: never inserts a duplicate even on repeated/racing calls.
|
||||||
|
return SavedItem::firstOrCreate([
|
||||||
'user_id' => auth()->id(),
|
'user_id' => auth()->id(),
|
||||||
'saveable_id' => $this->id,
|
'saveable_id' => $this->id,
|
||||||
'saveable_type' => get_class($this),
|
'saveable_type' => get_class($this),
|
||||||
@@ -48,7 +54,9 @@ public function addSave()
|
|||||||
|
|
||||||
public function removeSave()
|
public function removeSave()
|
||||||
{
|
{
|
||||||
if (!$this->getIsSavedAttribute()) return false;
|
if (!auth()->check()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return SavedItem::where([
|
return SavedItem::where([
|
||||||
'user_id' => auth()->id(),
|
'user_id' => auth()->id(),
|
||||||
|
|||||||
Reference in New Issue
Block a user