📜  laravel where multiple conditions on single colmn - PHP(1)

📅  最后修改于: 2023-12-03 15:17:13.189000             🧑  作者: Mango

Laravel where multiple conditions on single column - PHP

In Laravel, you can use the where method to apply multiple conditions on a single column when querying the database. This allows you to filter your results based on different criteria without having to write complex SQL queries.

Syntax

The syntax for applying multiple conditions on a single column in Laravel is as follows:

$ModelName::where(function ($query) {
    $query->where('column', 'condition1')
          ->where('column', 'condition2')
          ->orWhere('column', 'condition3');
})
->get();

Here's a breakdown of the different parts of the syntax:

  • ModelName: Replace this with the name of your Eloquent model class.
  • column: Replace this with the name of the column you want to apply the conditions on.
  • condition1, condition2, condition3: Replace these with the specific conditions you want to apply.
Example

Let's say we have a users table with a status column, and we want to retrieve all the users whose status is either "active" or "pending". Here's how you can do that:

$users = User::where(function ($query) {
    $query->where('status', 'active')
          ->orWhere('status', 'pending');
})
->get();

This query will return a collection of User models where the status is either "active" or "pending".

Conclusion

Using the where method with multiple conditions on a single column in Laravel allows you to easily filter your query results based on different criteria. This can be a powerful tool when building complex queries in your PHP application.