skip to Main Content

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


  1. You can loop though your columns to check with whereNull method like below,

    $columns = ['field_x','field_y'];
    
    $rules = Rule::exists('users', 'id');
    
    foreach($columns as $column){
        $rules->whereNull($column);
    }
    $rulesFinal = $rules;
    
    Login or Signup to reply.
  2. Unfortunately, Laravel’s Eloquent ORM doesn’t support passing an array of columns to the whereNull method directly. However, you can chain multiple whereNull clauses together like this:

    Rule::exists('users', 'id')
        ->whereNull('field_x')
        ->whereNull('field_y');
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search