File: //home/armgroup/libs/app/Http/Livewire/Frontend/Search/AddToFavorite.php
<?php
namespace App\Http\Livewire\Frontend\Search;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\Favorite;
use App\Models\Product;
use Livewire\Component;
class AddToFavorite extends Component
{
use ConvertEmptyStringsToNull, General;
public Product $product;
public $added_to_favorite = false;
protected $listeners = ['removeFavorite'];
public function removeFavorite($product_id)
{
if ($product_id == $this->product->id) {
$this->added_to_favorite = false;
}
}
public function render()
{
if (Favorite::where('user_id', auth()->id())
->where('favoritable_type', Product::class)
->where('favoritable_id', $this->product->id)
->count()) {
$this->added_to_favorite = true;
}
return view('livewire.frontend.search.add-to-favorite');
}
public function toggleFavorite()
{
if (! auth()->check()) {
$this->ajaxDoneMessage('برای افزودن محصول به علاقهمندیها ابتدا باید وارد سایت شوید.', 'error');
} else {
$favorite = Favorite::where('user_id', auth()->id())
->where('favoritable_type', Product::class)
->where('favoritable_id', $this->product->id)
->first();
if ($favorite) {
$favorite->delete();
$this->ajaxDoneMessage('محصول با موفقیت از علاقهمندیها حذف شد.', 'info');
$this->added_to_favorite = false;
} else {
Favorite::create([
'user_id' => auth()->id(),
'favoritable_type' => Product::class,
'favoritable_id' => $this->product->id,
]);
$this->ajaxDoneMessage('محصول با موفقیت به علاقهمندیها اضافه شد.');
$this->added_to_favorite = true;
}
$this->emit('favoritesChanged', auth()->user()->favorites()->count());
}
}
}