Laravel whereIn & whereNotIn Eloquent Query

For the creation of web applications, many developers use the Laravel PHP framework. The development process can be sped up and made more effective with the wide range of tools and capabilities it offers. One of these characteristics is the object-oriented syntax interaction with the database that Eloquent ORM (Object-Relational Mapping) enables developers to use.

In this article, we will take a closer look at the whereIn and whereNotIn methods in Eloquent, which allow you to build queries based on an array of values.

whereIn Method

Eloquent’s whereIn method enables you to get database records where a given column’s value appears within a predefined array of values. This is especially helpful if you need to obtain data based on various values. Consider, for instance, a situation where you want to obtain all users with the identities “John” or “Jane.” You can use the whereIn technique in the following ways to achieve this:

$users = User::whereIn('name', ['John', 'Jane'])->get();

In the example above, the whereIn method takes two parameters: the first parameter is the name of the column you want to query, and the second parameter is the array of values to search for. The result of this query will be a collection of all users whose names are either ‘John’ or ‘Jane’.

whereNotIn Method

You can get records from the database where a certain column’s value is missing from a provided array of values by using Eloquent’s whereNotIn method. This is helpful if you wish to query without including specific values. Take the case when you need to get a list of all users whose names aren’t “John” or “Jane,” for instance. Use the whereNotIn method in the following ways to do this:

$users = User::whereNotIn('name', ['John', 'Jane'])->get();

In the example above, the whereNotIn method takes two parameters: the first parameter is the name of the column you want to query, and the second parameter is the array of values to exclude. The result of this query will be a collection of all users whose names are not ‘John’ or ‘Jane’.

Conclusion

As a result, Eloquent ORM by Laravel’s whereIn and whereNotIn methods offer a practical and adaptable technique for retrieving records based on an array of values. With only a few lines of code, these methods make it simple to construct sophisticated searches, whether you wish to include or exclude specific values. Making your development process more effective and streamlined, you can save time by adopting these techniques and simplify your code.

About Tech Flow Zone

Check Also

Laravel Copy Record using Eloquent Replicate

Laravel provides an elegant and simple way to copy a record using the Eloquent replicate …

Leave a Reply

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