where('id', 1) ->where(functi" /> where('id', 1) ->where(functi" /> where('id', 1) ->where(functi"/>

Laravel7 query wrap with "not"

33 Views Asked by At

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

There are 2 best solutions below

0
JohnSmith On

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');
1
kris gjika On

The specific example you have provided is better done as:

$q->where('id', 1)
  ->whereNotIn('tag', ['foo', 'bar']);