Search code examples
laravelfilteringlaravel-livewire

How to Filter data when input is NULL it will NOT add the query Laravel 9?


i want to make Filtering data with Laravel 9 and Livewire. the goal is when input is NULL the query will not search the input.

$barangs = Barang::with('supplier', 'merk', 'kategori')
            ->where('supplier_id', $this->supplierID)->where('merk_id', $this->merkID)->where('kategori_id', $this->kategoriID)->get();

so, if the $this->supplierID is NULL it will be like this below

$barangs = Barang::with('supplier', 'merk', 'kategori')
            ->where('merk_id', $this->merkID)->where('kategori_id', $this->kategoriID)->get();

how to achieve that ? thankyou so much for the answer


Solution

  • You can do it in two different ways

    Traditional if()

    $barangQuery = Barang::with('supplier', 'merk', 'kategori')
        ->where('merk_id', $this->merkID)
        ->where('kategori_id', $this->kategoriID);
    
    if ($this->supplierID) {
        $barangQuery->where('supplier_id', $this->supplierID);
    }
    
    $barangs = $barangQuery->get();
    

    The other solution is using when()

    $barangs = Barang::with('supplier', 'merk', 'kategori')
        ->where('merk_id', $this->merkID)
        ->where('kategori_id', $this->kategoriID)
        ->when($this->supplierID, function ($query) {
            $query->where('supplier_id', $this->supplierID);
        })
        ->get();