Hello Geek, The topic for today is how to use the wherein query in Laravel Eloquent. How does the Laravel model work with array queries? I’ll give you a simple example of how to use the Laravel query builder. Laravel eloquent where in array can be used.
In Laravel 6, 7, 8, and 9, you can easily use the wherein eloquent method.
If you need to use sql wherein query in laravel, you can do so using an array. To use a sql wherein query, Laravel provides wherein(). We only need to pass two arguments to wherein(), one for the column name and another for an array of ids or whatever we want.
The syntax for wherein query in Laravel is shown below:
whereIn(Coulumn_name, Array);
Now I’ll show you three examples of wherein queries in Laravel applications. So, let’s see how those examples work.
Example 1:
SQL Query:
SELECT *
FROM users
WHERE id IN (4, 5, 6)
Laravel Query:
public function index()
{
$users = User::select("*")
->whereIn('id', [4, 5, 6])
->get();
dd($users);
Example 2
Here’s another example of a query. You can use comma separated string values. You can do the following:
public function index()
{
$myString = '1,2,3';
$myArray = explode(',', $myString);
$users = User::select("*")
->whereIn('id', $myArray)
->get();
dd($users);
}
Example 3
public function index()
{
$users = DB::table('users')
->whereIn('name', ['Hardik', 'Vimal', 'Harshad'])
->get();
dd($users);
}
All the best nerd!