'How do I chain multiple where and orWhere clause in laravel from an Array [duplicate]

I have an array

$user_lgas = ['lga1', 'lga2', 'lga3', ...];

I want to write a scopeSearch to get records base on user lgas something like

$query->where('lga', $user_lgas[0])->orWhere('lga', $user_lgas[1])->orWhere('lga', $user_lgas[2]) ...

I want to generate this query dynamically from the array, but the logic is kind of complicated for me. Please any Help



Solution 1:[1]

As per the Laravel Documentation you should be able to use whereIn() or whereNotIn() with an array.

$users = DB::table('users')
                    ->whereIn('id', array(1, 2, 3))->get();
 
$users = DB::table('users')
                    ->whereNotIn('id', array(1, 2, 3))->get();

So for your example

$query->whereIn('lga',$user_lgas)->get();

For more details see: Database: Query Builder

Solution 2:[2]

You can just use a whereIn instead.

$query->whereIn('lga', $user_lgas)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CloudTheWolf
Solution 2 Bernard Wiesner