Search code examples
phplaraveleloquent

Laravel Where Clause not working for Null values


I have a customers table and Customer as Model. I am trying to get all the customers except customer category with id 1. The customer_category_id can be nullable.

I have following query.

Customer::where('customer_category_id', '!=', 1)->with('customerMeta')->get();

Above query doesn't give the customers with null customer category id. What would be the reason ?

I need all the customers with category null or category not equals to 1

Any kind of suggestions are appreciated.


Solution

  • This should work:

    Customer::where(function ($query) {
                $query->where('customer_category_id', '!=', 1)
                      ->orWhereNull('customer_category_id')
            })
            ->with('customerMeta')
            ->get();
    

    Good luck!