I have a report area for which I am using livewire, I need the reports to be filtered by product category, this works for me as long as the ‘all’ option that I have inside a select is not selected:
<span>Seleccionar categoría</span>
<div class="form-group">
<select class="form-control" wire:model="categoriaId" name="categoria" id="categoriaId">
<option value="">Seleccionar categoría</option>
<option value="0">Todas</option>
@foreach ($categorias as $categoria)
<option value="{{ $categoria->id }}">{{ $categoria->nombre }}</option>
@endforeach
</select>
</div>
For some reason whenever I select any option inside the foreach
it does filter properly, but when i do the option in which the value is 0, it does not bring me all products.
Here’s what’s inside my controller:
public function Articulos()
{
//dd($this);
if ($this->artcero == 'si') {
$this->data = Articulo::join('categorias as c', 'c.id', 'articulos.categoria_id')
->when($this->categoriaId !== 0, function($query) {
return $query->where('categoria_id', $this->categoriaId)
->select('articulos.*', 'c.nombre as catnom');
})
->when($this->categoriaId == null, function($query) {
return $query->select('articulos.*', 'c.nombre as catnom');
})
->get();
return $this->data;
} elseif ($this->artcero == 'no') {
$this->data = Articulo::join('categorias as c', 'c.id', 'articulos.categoria_id')
->when($this->categoriaId !== 0, function($query) {
return $query->where('categoria_id', $this->categoriaId)
->select('articulos.*', 'c.nombre as catnom');
})
->when($this->categoriaId == null, function($query) {
return $query->select('articulos.*', 'c.nombre as catnom');
})
->where('stock', '>', 0)
->get();
return $this->data;
}
And:
public $nombreComponente, $data, $categoriaId, $alm;
public function mount()
{
$this->nombreComponente = 'Reportes';
$this->data = [];
$this->artcero = 'si';
$this->alm = [];
}
public function render()
{
$this->Articulos();
return view('livewire.articuloreports.articulocomponent', [
'articulos' => Articulo::get(),
'almacenes' => Almacen::get(),
'categorias' => Categoria::get()
])->extends('adminlte::page')
->section('content');
}
using dd()
the categoriaId comes back null, and I don’t really know what I’m doing wrong
3
Answers
Fixed it by filtering by category first, like this:
Are you tried modify this
to this
to see the result?