File: /home/armgroup/libs/app/Http/Livewire/Frontend/Product/Rate.php
<?php
namespace App\Http\Livewire\Frontend\Product;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\Product;
use App\Models\Score;
use Livewire\Component;
class Rate extends Component
{
use ConvertEmptyStringsToNull, General;
public Product $product;
public $score;
public function mount()
{
if (auth()->check()) {
$this->score = auth()->user()->scores()
->where('scorable_type', Product::class)
->where('scorable_id', $this->product->id)
->first()
?->score;
}
}
public function rate($score)
{
if (! auth()->check()) {
$this->ajaxDoneMessage('برای امتیازدهی باید وارد سایت شوید', 'error');
return;
}
if (! in_array($score, [1, 2, 3, 4, 5])) {
return;
}
Score::updateOrCreate([
'user_id' => auth()->id(),
'scorable_id' => $this->product->id,
'scorable_type' => Product::class,
], ['score' => $score]);
$this->score = $score;
$scores = $this->product->scores()->get();
$this->emit('changedRateResult', $scores->count(), round($scores->avg('score'), 1));
$this->ajaxDoneMessage('باتشکر، امتیاز شما با موفقیت ثبت شد');
}
public function render()
{
return view('livewire.frontend.product.rate');
}
}