In this tutorial, we will learn how you can use where condition in laravel eloquent. It is very easy and short as compared to SQL raw query. We will also discuss multiple where conditions. Let’s start with it.
What is Laravel Eloquent?
Before proceeding further, you should familiar with what is eloquent?
Eloquent is an ORM (Object Relation Mapper) and it helps to interact with the database and get the records from the database table according to your query. Eloquent has the ability to insert new records, delete, update records with the built-in very easy functions.
A big advantage of eloquent is that we can easily manage the relationship between two tables or more and in a very short query. We don’t need to write the long query for the two tables’ joins the same as in the SQL query.
Let’s start with the Where condition to using in the query.
Where Condition in Laravel Eloquent
Eloquent where condition use to get data from database based the specific conditions. We already knew about SQL query with where condition and it is very long. So eloquent provide you short, fast, easily retrieves data from the database table. We can also add multiple where condition and use them in the query builder.
SQL Query Syntax:
Select * FROM table_name WHERE column_name = 'value'
Eloquent Query Syntax
where('COLUMN_NAME', 'OPERATOR', 'VALUE')
See the difference above, eloquent is very easy to use and learn and it is fast also.
Let’s use the where condition in laravel for example.
Method 1: With Operator
In this method, we will use the operator inside the where condition. See the example below.
Method 2: Without Operator
In both above examples will return the same result, only the difference between is an operator. In the first example, we had used OPERATOR (=) to check the status column and in the second example we haven’t used OPERATOR because it is the magic of eloquent and it understands automatically for the operator. But it will only work for Equal Operator (=). For other operators, you have to define.
Note: Clarifing again, without operator query only work for EQUAL OPERATOR (=).
Multiple Where Condition in Laravel Eloquent
If you have multiple conditions to check in the database table then you have to write multiple where condition in the query. Let’s see the example.
This will return the result with an exact match of all conditions with the EQUAL OPERATOR.
But what if you want to add a comparison operator and want to compare the value, So let’s see the following example for that.
You can also do the following.
More Laravel Articles
If you have any questions or you stuck at any point please ask me in the comment section. I’ll happy to help you with that.