Laravel WhereIn with 2 Examples (Quick Answer)

November 28, 2023
Laravel
Laravel WhereIn with 2 Examples (Quick Answer)

In this article, you will learn how you use laravel whereIn with different examples. We will cover how to use laravel whereIn and will also share some examples of it as well.

By the end of the article, you will be able to understand and perform queries using wherein in laravel.

What does whereIn in do?

Just like where laravel, the wherein works in the same way. The only difference is that you can search at the same times for different values in the same column.

Syntax of whereIn in laravel:

The syntax of whereIn is quite simple, first, we have the column name followed by the array.

whereIn(column_name, Array);

Let’s discuss examples to have a better understanding.

Example 1:

Let’s say we have the users and we want users whom names are johnmethaw or alexey only.

The SQL query of it will be like:

Select *
 from users
 where name in ('john','methaw','alexey'); 

And in laravel eloquent we can write in this way:

public function index()
{
    $all_users = User::select("*")
                    ->whereIn('name',['john','methaw','alexey'])
                    ->get();
  
    dd($all_users);                    
}

This will give us all the users which have john, methaw or alexey only as the name.

Example 2:

Let me give you an example with the  DB class as well.

public function index()
{
    $all_users = DB::table('users')
                    ->whereIn('name', ['john','methaw','alexey'])
                    ->get();
  
    dd($all_users);                    
}

The output will be the same that all the users which have john, methaw or alexey as the name.

Check the article on whereNotIn as well.

Conclusion:

Hope you have learned today how to use the whereIn in laravel eloquent with the different examples.

If you want to learn how to use whereNotIn as well please check this article.

Let me know if you have any related questions in the comments.

See you in the next one!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon