Hello people. First of all, it is not a livewire problem, but of my knowledge.
I’ve had a hard time making a situation work. I have some selects and I am trying to make my component set up a query through them. Currently, you can select wired:model and directly in the render, if not selected for null, add a query. I’m sure this is completely wrong, but I can’t seem to do it any other way.
Currently it works, but I know it’s done very wrong. Could someone direct me to the right path?
class ProductList extends Component
{
use WithPagination;
public $sortBy;
public $perPage;
public $parameters;
public $categorie;
public $subcategorie;
public $min;
public $max;
public function mount()
{
$this->fill([
'parameters' => [
'section' => request()->section,
'categorie' => request()->categorie,
'subcategorie' => request()->subcategorie,
],
]);
}
public function updatingSortBy()
{
$this->resetPage();
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
$section = $this->parameters['section'];
$categorie = $this->parameters['categorie'];
$subcategorie = $this->parameters['subcategorie'];
$products = new Product;
if($section){
$products = $products->whereHas('sections', function ($products) use ($section){
$products->where('slug', $section);
});
}
if($categorie){
$products = $products->whereHas('categories', function ($products) use ($categorie){
$products->where('slug', $categorie);
});
}
if($subcategorie){
$products = $products->whereHas('subcategories', function ($products) use ($subcategorie){
$products->where('slug', $subcategorie);
});
}
if($this->min !== null){
$products = $products->where('price', '>=', $this->min);
}
if($this->max !== null){
$products = $products->where('price', '<=', $this->max);
}
$products->with('categories', 'subcategories');
if($this->perPage !== null){
$perPage = $this->perPage;
session()->put('perPage', $this->perPage);
}elseif (session('perPage')) {
$perPage = session('perPage');
}else{
$perPage = config('shop.perPage');
}
if($this->sortBy !== null){
switch ($this->sortBy) {
case 'sortByAZ':
$products = $products->orderBy('name', 'ASC');
break;
case 'sortByZA':
$products = $products->orderBy('name', 'DESC');
break;
case 'sortByLH':
$products = $products->orderBy('price', 'DESC');
break;
case 'sortByHL':
$products = $products->orderBy('price', 'ASC');
break;
default:
$products = $products->orderBy('name', 'ASC');
}
}
if($this->sortBy == null){
$products = $products->orderBy('name', 'ASC')->paginate($perPage);
}else{
$products = $products->paginate($perPage);
}
return view('livewire.shop.product-list', compact(
'products'
));
}
}