Laravel Query Builder: Using ‘AND’ and ‘OR’ Operators

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM provides a beautiful, simple ActiveRecord implementation for working with your database. However, when you need to build more complex queries, you lean on the query builder’s might. In Laravel, the query builder allows you to construct database queries with PHP methods. This tutorial will explore how to leverage the ‘AND’ and ‘OR’ logical operators within the Laravel Query Builder.

Understanding Logical Operators

In the context of database queries, logical operators are used to combine multiple conditions. The ‘AND’ operator allows you to specify that only the records that meet all the combined conditions should be included in the results, while the ‘OR’ operator will include records if any of the conditions are met.

Getting Started with ‘AND’ Operator

Let’s begin with the ‘AND’ operator. By default, when you chain multiple conditions in the Laravel Query Builder, they are combined using the ‘AND’ operator.

$users = DB::table('users')
             ->where('status', '=', 'active')
             ->where('type', '=', 'admin')
             ->get();

In this example, we are selecting all users that are active and admins. Now, let’s add an age condition to this query.

$users = DB::table('users')
             ->where('status', '=', 'active')
             ->where('type', '=', 'admin')
             ->where('age', '>', 30)
             ->get();

This will return all the active admin users who are older than 30 years.

Utilizing the ‘OR’ Operator

To implement an ‘OR’ condition, you will use the orWhere method:

$users = DB::table('users')
             ->where('status', '=', 'active')
             ->orWhere('type', '=', 'admin')
             ->get();

This retrieves all the users who are either active or admins.

Combining ‘AND’ and ‘OR’

Let’s consider a more complex scenario where you need a combination of ‘AND’ and ‘OR’ operators.

$users = DB::table('users')
             ->where('status', '=', 'active')
             ->where(function($query) {
                 $query->where('type', '=', 'admin')
                       ->orWhere('age', '>', 30);
             })
             ->get();

Here, we are looking for active users who are either admins or are older than 30 years. We are achieving this by using a closure to group the conditions that should be treated together.

Advanced Conditional Clauses

Laravel also allows you to write more advanced conditional queries, for example, using the when method. The when method allows you to conditionally add clauses to your query based on the truthiness of the first argument.

$isAdmin = true;

$users = DB::table('users')
             ->where('status', '=', 'active')
             ->when($isAdmin, function ($query) {
                 return $query->where('type', '=', 'admin');
             })
             ->get();

If $isAdmin is true, it will include an additional condition to check if the user type is ‘admin’.

Parameter Grouping and Subqueries

Sometimes, you may need to create more complex logical groups or even subqueries using ‘AND’ and ‘OR’. You can achieve this with the Laravel Query builder as well.

$users = DB::table('users')
             ->where('status', 'active')
             ->where(function ($query) {
                 $query->where('votes', '>', 100)
                       ->orWhere('title', '=', 'Admin');
             })
             ->get();

And for subqueries:

$sub = DB::table('users')
          ->selectRaw('count(*) as user_count, status')
          ->where('status', '<>', '1')
          ->groupBy('status');

$users = DB::table(
             DB::raw("({$sub->toSql()}) as sub")
         )->mergeBindings($sub->getQuery())
          ->get();

Don’t forget that when dealing with raw statements or subqueries, you should merge bindings to prevent SQL injection attacks.

Conclusion

Understanding how to use ‘AND’ and ‘OR’ operators within Laravel’s Query Builder can be crucial for building complex queries. This tutorial covered the basics and provided examples that can be used as a starting point for writing more complex database queries in your Laravel applications. Always remember to keep your queries as simple and readable as possible for maintenance and performance reasons. Happy querying!