Can I do Model->where('id', ARRAY) multiple where conditions?

PhpLaravel

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

Solution 2 - Php

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();

Solution 3 - Php

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();

Solution 4 - Php

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();

Solution 5 - Php

If you are searching by ID you can also use:

$items = Item::find(array_of_ids);

Solution 6 - Php

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

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

Solution 7 - Php

WHERE AND SELECT Condition In Array Format Laravel

use DB;

$conditions = array(
	array('email', '=', '[email protected]')
);
$selected = array('id','name','email','mobile','created');
$result = DB::table('users')->select($selected)->where($conditions)->get();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVudewView Question on Stackoverflow
Solution 1 - PhpLimon MonteView Answer on Stackoverflow
Solution 2 - Phpbehzad babaeiView Answer on Stackoverflow
Solution 3 - PhpGediminasView Answer on Stackoverflow
Solution 4 - PhpchanafdoView Answer on Stackoverflow
Solution 5 - PhpAyenew YihuneView Answer on Stackoverflow
Solution 6 - PhpSwastik MallikView Answer on Stackoverflow
Solution 7 - PhpArunView Answer on Stackoverflow