Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shadrix's avatar
Level 12

How to use whereNotNull in whereHas?

I'm not able to use whereNotNull in my query. I need to check if the column "fresh_until" is not null. If it is not null, we check the date as well.

->when($this->date, function ($query){
    $query->whereHas('food.date', function ($query){
        $query->where('valid_from', '<=', $this->date); //this works perfectly
        $query->whereNotNull('fresh_until') //this not
                     ->where('fresh_until', '>=', $this->date);
    });
})
0 likes
2 replies
Yorki's avatar
Yorki
Best Answer
Level 11

Should it returns rows where fresh_until is null? If so try this

->when($this->date, function ($query){
    $query->whereHas('food.date', function ($query){
        $query->where('valid_from', '<=', $this->date); 
        $query->where(function ($query) {
            $query->whereNull('fresh_until')
                ->orWhere('fresh_until', '>=', $this->date);
        });
    });
})
1 like
pardeepkumar's avatar

i think you may use like this

$query = DB::table('myTable')->select(DB::raw($columnNames));

foreach($columns as $column){
    $query->orWhereNotNull($column);
}

$result = $query->get();

Please or to participate in this conversation.