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

rene's avatar
Level 2

where('field', null) is not working

Hi,

The following query results in zero results:

$request->get('foobar') returns a null.

Foobar::where('user_id', 1)->where('second_id', $request->get('foobar'))->first();

This is possible, because the second_id may contain null-values. But it doesn't work. It's not recognizing the second_id. It gives zero results.

0 likes
5 replies
hxd's avatar

I tried this, and it works, maybe you should check $request->get('foobar') really return null?

$all = Permission::where('id', 10)->where('description', null)->get(); var_dump($all); exit;

or you can use whereNull, just add a judgement before use it.

RomainLanz's avatar

Hey @rene !

You should check if the value of $request->get('foobar') is null or not when writing your query.

$query = Foobar::where('user_id', 1)

if (!is_null($request->get('foobar'))) {
  $query->where('second_id', $request->get('foobar'));
}

$query->first();
edruid's avatar

The reason for the where('second_id', null) doesn't work is that in SQL null = null is falsy (actually null). Most, if not all, SQL dialects have a null safe comparison method; In MySQL it's <=> and PostgreSQL has IS NOT DISTINCT FROM So adding the comparator parameter to the where method should do the trick: (For mysql)

Foobar::where('user_id', 1)->where('second_id', '<=>', $request->get('foobar'))->first();

Please or to participate in this conversation.