ホーム > Laravel > How to Get A and (B or C) in Complex Condition Search in Laravel
Laravel

How to Get A and (B or C) in Complex Condition Search in Laravel

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents for Laravel articles

This article summarizes how to get A and (B or C) in complex condition search in Laravel.

At the beginning

In Laravel, it is possible to implement condition searches using where or orWhere,

In this article,

I will write about how to get users who are A and (B or C).

Specifically,

A: Email verified
B: Belongs to category 1
C: Belongs to category 5

Let's retrieve these users.

It means to retrieve users who are

"Email verified"

"Belong to category 1 or 5".

Things to know beforehand

How to perform AND search with multiple conditions in Laravel

How to perform OR search using orWhere in Laravel

Conclusion

Controller

$users = User::whereNotNull('email_verified_at')
    ->where(function($query){
        $query->where('category_id',1)
            ->orWhere('category_id',5);
    })
    ->get();

Explanation

Write the where condition to retrieve only users who have verified their email

->whereNotNull('email_verified_at')

Write the where condition for category 1 or category 5

->where(function($query){
    $query->where('category_id',1)
        ->orWhere('category_id',5);
})

Let's delve into this part.

It may look a bit complicated,

Since it is A and (B or C),

The part connecting A and (B or C) is written in where

// This part
->where(function($query){

What is $query?

$query is an argument used inside the function, so $q is also fine, but I think it's good to think of it as inheriting the search conditions inside the function.

Write (B or C) within the function

$query->where('category_id',1)
        ->orWhere('category_id',5);

Summary

I tried to cover complex condition search in Laravel.

By writing these multiple conditions, various condition searches (such as selecting multiple checkboxes) are possible.

However, there is also a method to specify multiple conditions in an array using whereIn, so consider if you can implement it with whereIn for the same column.

I hope this is helpful for someone.

For feedback or complaints, please contact me via Twitter DM.

That's all!

Related articles

How to perform AND search with multiple conditions in Laravel

Popular articles

Deploying a PHP7.4 + Laravel6 Project to AWS EC2

Implementing Breadcrumbs in Laravel using laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!