skip to Main Content

How to create "NOT" wrapped criteria, ie:

WHERE
  id=1 AND NOT (tag='foo' OR tag='bar')

I know I can wrap with closure

$q->where('id', 1)
  ->where(function ($iq) {
    $iq->where('tag', 'foo')
      ->orWhere('tag', 'bar');
  });

Something like this (which does not work):

$q->where('id', 1)
  ->where('!=', function ($iq) {
    $iq->where('tag', 'foo')
      ->orWhere('tag', 'bar');
  });

Edit:
I have Laravel7

2

Answers


  1. Chosen as BEST ANSWER

    Laravel 10 has where not clause but Laravel 7 does not.

    But this works:

    $q->where('id', 1)
      ->where(function ($iq) {
        $iq->where('tag', 'foo')
          ->orWhere('tag', 'bar');
      }, null, null, 'and not');
    

  2. The specific example you have provided is better done as:

    $q->where('id', 1)
      ->whereNotIn('tag', ['foo', 'bar']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search