File: /home/armgroup/libs/app/Http/Livewire/Frontend/Comments.php
<?php
namespace App\Http\Livewire\Frontend;
use App\Http\Livewire\ConvertEmptyStringsToNull;
use App\Http\Livewire\General;
use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;
class Comments extends Component
{
use ConvertEmptyStringsToNull, General, WithPagination;
protected $paginationTheme = 'bootstrap';
protected $listeners = ['reply'];
public $commentableT;
public $commentableI;
public $name;
public $email;
public $comment;
public $parent = null;
public $parent_name = null;
public function mount()
{
if (auth()->check()) {
$this->name = auth()->user()->name;
$this->email = auth()->user()->email;
}
}
protected function rules()
{
return [
'name' => 'required|string|max:250',
'email' => 'nullable|string|email|max:250',
'comment' => 'required|string|max:60000|min:5',
];
}
public function render()
{
return view('livewire.frontend.comments', [
'comments' => Comment::where('commentable_type', $this->commentableT)
->where('commentable_id', $this->commentableI)
->where('status', Comment::STATUS_APPROVED)
->whereNull('parent_id')
->with('activeChildren')
->latest()
->paginate(10),
]);
}
public function store()
{
$this->validate();
DB::transaction(function () {
if (auth()->check()) {
$user = auth()->user();
$user->name = $this->name;
$user->email = $this->email;
if ($user->isDirty()) {
$user->update();
}
}
Comment::create([
'user_id' => auth()->check() ? auth()->id() : null,
'parent_id' => $this->parent,
'commentable_id' => $this->commentableI,
'commentable_type' => $this->commentableT,
'name' => $this->name,
'email' => $this->email,
'comment' => $this->comment,
]);
$this->comment = null;
if (! auth()->check()) {
$this->name = null;
$this->email = null;
}
$this->ajaxDoneMessage('نظر شما با موفقیت ثبت شد');
});
}
public function reply($parent_id)
{
$check = Comment::where('commentable_type', $this->commentableT)
->where('commentable_id', $this->commentableI)
->where('status', Comment::STATUS_APPROVED)
->whereNull('parent_id')
->where('id', $parent_id)
->first();
if ($check) {
$this->parent = $parent_id;
$this->parent_name = $check->name;
$this->dispatchBrowserEvent('move-to-reply');
} else {
$this->parent = null;
$this->parent_name = null;
}
}
public function previousPage()
{
$this->setPage(max($this->page - 1, 1));
$this->emit('scrollTop');
}
public function nextPage()
{
$this->setPage($this->page + 1);
$this->emit('scrollTop');
}
public function gotoPage($page)
{
$this->setPage($page);
$this->emit('scrollTop');
}
}