WhereIn Laravel Query with Example


WhereIn Laravel Query with Example

Hi friends, in this tutorial you will learn how to execute the whereIn laravel query. This is a very important feature and required while getting data based on more than one value of a column from a particular table in the database. On the other hand, if you notice then you might know that it is almost similar to the NOT IN operator in MySQL. In SQL, when we fetch data based on multiple values of a column from a table then we get the data by passing an array of column values inside the NOT IN() with where condition the SQL query as shown below

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

But in laravel, we can do the same thing with the help of the whereIn() condition of laravel query builder.

Also read, Get sum of column values in laravel with example

Below is an example of whereIn laravel query

Here, we will get the data based on the condition array from a table name “product_info”

DDL information of the table

CREATE TABLE product_info (
id int(10) NOT NULL AUTO_INCREMENT,
product varchar(255) NOT NULL,
quantity varchar(255) NOT NULL,
price varchar(255) NOT NULL,
created_at timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

Below is an image of the table for your reference

We will put the column values in the form of an array as shown below

$quantity_array = [3,6];

Query to get data:-

DB::table('product_info')->whereIn('quantity',[3,6])->get();
//or
DB::table('product_info')->whereIn('quantity',$quantity_array)->get();

Output:-

ProductQuantityPrice
Pen310
Book630

Conclusion:- I hope this tutorial will help you to understand the overview. If there is any doubt then please leave a comment below


Leave a Comment