Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

Is it possible to add a global `AND` condition to an Eloquent query?

Hello

I have this simple query that I cant change it unfortunately but I can add on it :

echo User::orWhereIn('id',[1,2,5])
            ->orWhereIn('id',[1,92,5,9,6,96,9])
            ->toSql();

 SQL result is :
select * from "users" where ("id" in (?, ?, ?) or "id" in (?, ?, ?, ?, ?, ?, ?)) and "users"."deleted_at" is null

In this case the where parentheses has "id" in (?, ?, ?) or "id" in (?, ?, ?, ?, ?, ?, ?) which is okay

The problem is when I add ->where('name','ilike','%mod%')

the result is:

        echo User::orWhereIn('id',[1,2,5])
            ->orWhereIn('id',[1,92,5,9,6,96,9])
            ->where('name','ilike','%mod%')
            ->toSql();

SQL result is :
select * from "users" where ("id" in (?, ?, ?) or "id" in (?, ?, ?, ?, ?, ?, ?) and "name"::text ilike ?) and "users"."deleted_at" is null

The sql result I need is : ...where( ... OR ...) AND "name"::text ilike ?

select * from "users" where ("id" in (?, ?, ?) or "id" in (?, ?, ?, ?, ?, ?, ?)) and "name"::text ilike ? and "users"."deleted_at" is null

Hope it's clear!

Any idea ???

0 likes
5 replies
Sinnbeck's avatar

Curious why you cannot change it? Maybe replace it then? Write a completely new query that replaces the old variable?

1 like
GodziLaravel's avatar

@Sinnbeck In fact it's a big file (search filter) I tried to avoid touching it but I think I have no choice!

Sinnbeck's avatar

@GodziLaravel Sadly yes. You need to scope it

User::where(function($query) {
         $query->whereIn('id',[1,2,5])
            ->orWhereIn('id',[1,92,5,9,6,96,9])
          })
            ->where('name','ilike','%mod%')
            ->toSql();
1 like
MohamedTammam's avatar
User::where(function($q){
      $q->WhereIn('id',[1,92,5,9,6,96,9])
       ->orWhere('name','ilike','%mod%')
    })
  ->where('name','ilike','%mod%')
  ->toSql();
1 like
tisuchi's avatar

@godzilaravel How about this?


User::where(function($query) use ($id1, $id2, $id3) {
    $query->whereIn('id', [$id1, $id2, $id3])
          ->orWhereIn('id', [$id4, $id5, $id6, $id7, $id8, $id9, $id10]);
})
->where('name', 'like', $name)
->whereNull('deleted_at')
->get();

Please or to participate in this conversation.