Sling Academy
Home/PHP/Using Multiple ‘WHERE’ Conditions in Laravel Query Builder

Using Multiple ‘WHERE’ Conditions in Laravel Query Builder

Last updated: January 16, 2024

Introduction

Laravel, as a PHP framework, facilitates elegant syntax and robust features for interacting with databases. Laravel’s Query Builder provides a convenient wrapper around SQL queries, making it simple to perform complex database operations. In this tutorial, we dive into the use of multiple WHERE conditions within Laravel Query Builder to filter results efficiently. Whether you are just starting out or seeking to enhance your database querying skills in Laravel, this guide is designed to provide clear examples from the basic to the advanced functionalities of the Query Builder.

Basic ‘WHERE’ Conditions

Laravel’s Query Builder comes with a fluent interface to add WHERE conditions to your database queries. Here’s how you start with a simple condition:

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

This query retrieves all users with an ‘active’ status from the ‘users’ table.

Chaining Multiple ‘WHERE’ Conditions

If you want to add more than one condition, you can chain the where clauses together:

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

It returns active users who are also admins.

Using ‘orWhere’ to Broaden Query Results

When you need to include rows that match either condition, use orWhere:

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

This fetches users who are either active or guests.

Grouping ‘WHERE’ Conditions

Sometimes you may need to apply logical grouping to the conditions:

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

This selects active users who are either admins or have more than 100 votes.

Advanced ‘WHERE’ Methods

Laravel also provides advanced methods such as whereBetween, whereIn, and whereNull.

Using ‘whereBetween’

$users = DB::table('users')
    ->whereBetween('votes', [1, 100])
    ->get();

This command will return users with vote counts between 1 and 100.

Utilizing ‘whereIn’

$users = DB::table('users')
    ->whereIn('id', [1, 2, 3])
    ->get();

It retrieves users with specific IDs – 1, 2, or 3.

Consider ‘whereNull’

$users = DB::table('users')
    ->whereNull('deleted_at')
    ->get();

This will select users who haven’t been marked as deleted.

Join Clauses with ‘WHERE’ Conditions

Combining joins and WHERE conditions is also quite straightforward:

$orders = DB::table('orders')
    ->join('users', 'users.id', '=', 'orders.user_id')
    ->where('users.status', 'active')
    ->select('orders.*')
    ->get();

This will get all orders placed by active users.

Using Subquery ‘WHERE’ Conditions

You can even push the boundary by using subqueries within your WHERE conditions:

$users = DB::table('users')
    ->whereExists(function ($query) {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

The above snippet fetches users who have at least one order.

Conclusion

In this guide, we explored the dynamics of using multiple WHERE conditions in Laravel’s Query Builder. Through well-structured examples, we have seen how these conditions can refine our database queries to fetch precise data. Always strive to utilize Laravel’s eloquent methods to make your database interactions more readable, maintainable, and efficient.

Next Article: How to View Raw SQL Query Generated by Laravel Query Builder

Previous Article: Laravel Query Builder: Find rows where column is null/not null

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