Search code examples
sqllaravellaravel-8laravel-7laravel-6

WhereColumn null in laravel


I need compare two columns in table, but if one least is null, the query return empty.

id name original_price sale_price
1 Shampoo 2.30 NULL
$this->products = Product::whereColumn('original_price', '!=', 'sale_price')->get();

Solution

  • If you want such query returns also Null value(s) you should use orWhereNull

    $this->products = Product::whereColumn('original_price', '!=', 'sale_price')
                ->orWhereNull("original_price")
                ->orWhereNull("sale_price")
                ->get()
    

    BTW : if both are Null, fields are equal but query will not be empty