How can I check multiple fields in Laravel that they are not null? I’m thinking of writing my multiple fields check with multiple whereNull methods one after the other:
Rule::exists('users', 'id')
->whereNull('field_x')
->whereNull('field_y')],
Intuitively I would have thought that you can pass an array to the whereNull function. Unfortunately this is not possible. Are there other ways to do this?
This would work: ->whereNotNull(['field_x','field_y'])
but i need to the check that this fields are null. Like this: ->whereNull(['field_x','field_y'])
2
Answers
You can loop though your columns to check with
whereNull
method like below,Unfortunately, Laravel’s Eloquent ORM doesn’t support passing an array of columns to the
whereNull
method directly. However, you can chain multiplewhereNull
clauses together like this:This will effectively check that both ‘field_x’ and ‘field_y’ are null. It’s slightly more verbose, but it will achieve the desired outcome.