Sling Academy
Home/PHP/Laravel Query Builder: ‘GREATER THAN’ and ‘LESS THAN’ Operators

Laravel Query Builder: ‘GREATER THAN’ and ‘LESS THAN’ Operators

Last updated: January 16, 2024

Introduction

In the world of web development, database queries form the backbone of dynamic applications, and the Laravel PHP framework is no exception. Its eloquent and expressive syntax, stemming from the Query Builder, allows for writing database queries efficiently and with ease. In this tutorial, we’ll dive into using the ‘GREATER THAN’ and ‘LESS THAN’ operators within the Laravel Query Builder to fetch data accordingly.

Understanding the Basics

Let’s start with the basics. To leverage the Query Builder in Laravel, we first need to ensure we have a working Laravel environment.

Assuming you have Laravel installed, you can perform queries by using the DB facade.

use Illuminate\Support\Facades\DB;

Let’s say we have a table called ‘users’ and we want to find the users who are older than 18. Using Query Builder, the syntax would look like this:

$adultUsers = DB::table('users')->where('age', '>', 18)->get();

Similarly, to find users younger than 18, you replace ‘>’ with ‘<‘:

$youngUsers = DB::table('users')->where('age', '<', 18)->get();

Both ‘greater than’ and ‘less than’ operators work perfectly with numeric data types. Here, ‘get()’ is used to retrieve the results set as a Collection.

Comparing Dates

The Query Builder is also extremely capable when it comes to date comparison. For example, to find posts published after a certain date:

$recentPosts = DB::table('posts')->where('published_at', '>', now()->subDay())->get();

Note how we use Laravel’s ‘now()’ helper function, subtracting one day for the comparison.

Diving Deeper with Advanced Scopes

Scopes allow for encapsulating query logic to make your code cleaner and more reusable. Imagine you want to frequently query for active users in various places. You can define a local scope in the User model:

public function scopeActive($query)
{
 return $query->where('active', true);
}

And now, combining this with our age comparison:

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

We’ve chained the scope with ‘greater than’ operation seamlessly!

Using ‘GREATER THAN’ and ‘LESS THAN’ in Joins

Join operations with conditions are straightforward in the Query Builder. Consider you have two tables, ‘orders’ and ‘users’, and you want to join them based on the user’s spending being greater than a given threshold. Here’s how:

$highSpenders = DB::table('orders')
->join('users', function ($join) {
 $join->on('orders.user_id', '=', 'users.id')
 ->where('orders.total', '>', 1000);
})
->get();

This snippet will join the two tables where the users’ order total is greater than 1000.

Complex Where Clauses

Sometimes, your conditional logic may be more complex and requires grouping of ‘where’ clauses. Laravel has got you covered:

$specialOffers = DB::table('products')
->where('is_special_offer', true)
->where(function ($query) {
 $query->where('price', '<', 50)
 ->orWhere('stock', '>', 100);
})
->get();

This will retrieve products that are special offers and either priced below 50 or have more than 100 in stock.

Conclusion

We have explored the ‘GREATER THAN’ and ‘LESS THAN’ operators in Laravel’s Query Builder through various examples. With these building blocks, you are well-equipped to construct more dynamic and complex database queries that will ultimately lead to more robust Laravel applications. Remember, understanding the fundamentals of Query Builder operations is crucial in crafting effective Laravel solutions. Happy coding!

Next Article: Laravel Query Builder: Select rows where IDs are in an array

Previous Article: Shared Locking in Laravel Query Builder: A Practical Guide

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