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

Dosmukhanbet's avatar

Where query column if column has value

Hi everyone, please help to solve below issue There is table with column date_from and date_to. date_to column is optional, so it might be null. I want to make query this column if it has value, if it is null no need to run query at all. Is there way to make query conditionally depending column value? I have tries as below but it does not work as expected.

trips()->with('user', 'a_point', 'b_point')
                                    ->where('date_from', '>=' , Carbon::today())
                                    ->where('date_from', '>=' , Carbon::parse($date)->format('Y-m-d'))
                                    ->where( function ( $query ) use ( $date ) {
                                        $query->whereNotNull( 'date_to' )
                                              ->orWhere('date_to', '<=' , Carbon::parse($date)->format('Y-m-d'));
                                    });
0 likes
5 replies
Sinnbeck's avatar

Do you mean if $date is null?

trips()->with('user', 'a_point', 'b_point')
                                    ->where('date_from', '>=' , Carbon::today())
                                    ->where('date_from', '>=' , Carbon::parse($date)->format('Y-m-d'))
                                    ->when($date, function($query, $date) {
                                        $query->where( function ( $subQuery ) use ( $date ) {
                                            $subQuery->whereNotNull( 'date_to' )
                                                  ->orWhere('date_to', '<=' , Carbon::parse($date)->format('Y-m-d'));
                                            });
                                    });
Dosmukhanbet's avatar

@sinnbeck nope $date will come from request, I mean make query depending upon date_to column value in the table. Is it possible?

MichalOravec's avatar

You use same date for date_from and date_to that's problem.

It's same as

$date = Carbon::parse($request->date)->toDateString();

->where('date_from', $date)->where('date_to', $date)
Dosmukhanbet's avatar

@michaloravec i want to make query where $date greater than date_from and lower than date_to, but date_to sometimes null, in this case query should return only $date greater than date_from

MichalOravec's avatar

@dosmukhanbet So your logic is opposite, you have problem with <= and >=

$date = Carbon::parse($request->date)->toDateString();

trips()->with('user', 'a_point', 'b_point')->where('date_from', '<=', $date)->where(function ($query) use ($date) {
    $query->where(function ($query) use ($date) {
        $query->whereNotNull('date_to')->where('date_to', '>=', $date);
    })->orWhereNull('date_to');
});

Please or to participate in this conversation.