MySQL Eloquent ORM - where clause: value could be null

1 day ago 7
ARTICLE AD BOX

I'm a bit unsure about how to proceed with Eloquent ORM (Laravel 12) queries when a value COULD be NULL.

Normally, you would check for a NULL value with:

->whereNull("column")

But if you don't know whether the value is NULL at all, that's nonsense, of course. So you would use:

->where("column",value)

Laravel (I think from version 8 onwards?) automatically translates this into ‘column IS NULL’ in MySQL. Should you rely on this? To test it out, I like to check with Google Gemini, which offers the following option:

// app/Models/YourModel.php public function scopeWhereXIs($query, $search_value) { //if $search_value is NULL, use whereNull if ($search_value === null) { return $query->whereNull('x'); } //otherwise use where clause return $query->where('x', $search_value); }

So, the use of scopes. This means that in the query, you then use

->whereXIs($search_value_from_request)

However, this scope is only necessary if you do not want to trust Laravel.

What do you think? What would be the best practice here?

Greetings

Read Entire Article