<?php
namespace App\Http\Livewire\Pages;
use App\Models\Category;
use App\Models\Product;
use Livewire\Component;
use Livewire\WithPagination;
class ProductList extends Component
{
use WithPagination;
public $search = '';
public $categoryList = [];
public $category = '';
public $discountedOnly = false;
protected $queryString = ['search', 'category', 'discountedOnly'];
protected $paginationTheme = 'bootstrap';
public function mount()
{
if ($this->category != '') {
$this->categoryList = explode(',', $this->category);
}
}
public function updatingSearch()
{
$this->resetPage();
}
public function updatingCategoryList()
{
$this->resetPage();
}
public function updatingDiscountedOnly()
{
$this->resetPage();
}
public function updatedSearch($search)
{
$this->search = $search;
}
public function updatedCategoryList($categoryList)
{
$this->categoryList = $categoryList;
$this->category = implode(',', $this->categoryList);
}
public function updatedDiscountedOnly($discountedOnly)
{
$this->discountedOnly = $discountedOnly;
}
public function render()
{
$query = Product::query();
if ($this->search != '') {
$query->search($this->search);
}
if (sizeof($this->categoryList) > 0) {
$categoryList = $this->categoryList;
$query->whereHas('category', function ($q) use ($categoryList) {
$q->whereIn('slug', $categoryList);
});
}
if ($this->discountedOnly) {
$query->whereHas('discount', function ($q) {
$q->valid();
});
}
$products = $query->paginate(60);
$categories = Category::query()->hasActiveProduct()->orderBy('order', 'asc')->get();
return view('livewire.pages.product-list', [
'products' => $products,
'categories' => $categories,
]);
}
}