How to use whereIn Query in Laravel?

17222 views 1 year ago Laravel

In this article, i will share with you very simple but most used laravel query example how to use whereIn query in laravel eloquent. I will give you a very simple example of how to use whereIn in laravel.

If you want to match one record id given by id's array then you should be used whereIn for done these tasks.

Syntax

whereIn(Coulumn_name, Array);

Simple SQL Query

SELECT *
  	FROM articles
  	WHERE id IN (2,3,1)

Now, we will see how to use in laravel application in many ways

Example - 1

In this example, we will simply get some articles from the given by categories array.

public function index()
{
    $articles = Article::select("*")
        ->whereIn('category_id', [4, 5, 6])
        ->get();
    dd($articles);                    
}

Example -2

In this example, i will show you how to match comma-separated string values in whereIn().

public function index()
{
	$categoryIdString = '2,3,4';
    $categoryIds = explode(',', $categoryIdString);
    $articles = Article::select("*")
        ->whereIn('category_id', $categoryIds)
        ->get();
    dd($articles);                    
}

Example -3

You can also use a string array with whereIn().

public function index()
{
    $articles = Article::select("*")
        ->whereIn('tag_name', ['laravel', 'python', 'react', 'anguler', 'node'])
        ->get();
    dd($articles);                    
}

i hope it will be help a lot.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]