Build a bookmark/save feature.
Component
@php
new class extends Livewire\Component {
public int $postId;
public bool $bookmarked = false;
public function mount(int $postId): void
{
$this->postId = $postId;
$this->bookmarked = auth()->user()->bookmarks()->where('post_id', $postId)->exists();
}
public function toggle(): void
{
if ($this->bookmarked) {
auth()->user()->bookmarks()->detach($this->postId);
} else {
auth()->user()->bookmarks()->attach($this->postId);
}
$this->bookmarked = !$this->bookmarked;
}
}
@endphp