Sling Academy
Home/PHP/Laravel Query Builder: Using ‘AND’ and ‘OR’ Operators

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

Last updated: January 17, 2024

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!

Next Article: Laravel Query Builder: Using ‘ORDER BY’ Clause

Previous Article: Laravel Query Builder: Using ‘WHERE’ Clause

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array