111

The title says it all.

I get that I can do this :

DB::table('items')->where('something', 'value')->get()

But what I want to check the where condition for multiple values like so:

DB::table('items')->where('something', 'array_of_value')->get()

Is there an easy way of doing this?

miken32
  • 42,008
  • 16
  • 111
  • 154
Vudew
  • 1,235
  • 2
  • 9
  • 8

9 Answers9

161

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();
Limon Monte
  • 52,539
  • 45
  • 182
  • 213
65

You could use one of the below solutions:

$items = Item::whereIn('id', [1,2,..])->get();

or:

$items = DB::table('items')->whereIn('id',[1,2,..])->get();
behzad babaei
  • 1,111
  • 10
  • 11
32

If you need by several params:

$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
                  ->whereNotIn('id', $not_ids)
                  ->where('status', 1)
                  ->get();
Alex C
  • 516
  • 7
  • 15
Gediminas Šukys
  • 7,101
  • 7
  • 46
  • 59
11

You can use whereIn which accepts an array as second paramter.

DB:table('table')
   ->whereIn('column', [value, value, value])
   ->get()

You can chain where multiple times.

DB:table('table')->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->where('column', 'operator', 'value')
    ->get();

This will use AND operator. if you need OR you can use orWhere method.

For advanced where statements

DB::table('table')
    ->where('column', 'operator', 'value')
    ->orWhere(function($query)
    {
        $query->where('column', 'operator', 'value')
            ->where('column', 'operator', 'value');
    })
    ->get();
chanafdo
  • 5,016
  • 3
  • 29
  • 46
2

If you are searching by ID you can also use:

$items = Item::find(array_of_ids);
Ayenew Yihune
  • 1,059
  • 13
  • 19
1

It's work for me fetch just id then search in array

$shops = Shop::Where('user_id', Auth::id())->get('id');
$categories = Category::whereIn('shop_id',$shops)->paginate(7);
Sully
  • 392
  • 4
  • 14
0

You can do like this:

DB:table('table')->where([
    'column' => 'value',
    'column' => 'value',
    'column' => 'value',
])->get()

Instead of that:

DB:table('table')->where('column', 'value')
    ->where('column', 'value')
    ->where('column', 'value')
    ->get();
Rus Skazkin
  • 161
  • 2
  • 3
-1

$whereData = [['name', 'test'], ['id', '<>', '5']];

$users = DB::table('users')->where($whereData)->get();

-3

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
    array('email', '=', 'user@gmail.com')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();
Arun
  • 63
  • 1
  • 4
  • 1
    I think you misunderstood the question. OP was asking if there was a way to get the query builder to accept an array of VALUES as the where clause's value, not an array of conditions. – amphetamachine Jun 03 '20 at 16:33