Eloquent Query Builder — Laravel

The query builder is how Eloquent filters, sorts and counts rows without you writing SQL. You chain conditions (call methods one after another, joined with…

A librarian gets asked three things every day: which books can still be borrowed, which has the most copies, and how many titles are available. Book::all() from the last lesson fetches every book, and then you have to filter them yourself with if in PHP. The database can do it much faster, as long as you tell it what you're looking for.

That's the job of the query builder: how Eloquent filters, sorts and counts rows without you writing SQL. You chain the conditions one by one (where, orderBy). Chaining means calling methods one after another, joined with ->. Then you close the chain with one closing call, a method that actually sends the query to the database (get, first or count).

Picture the search form in a library catalogue. You tick "still in stock", then choose the order "most copies first". While you fill it in, nothing is searched yet. The search only runs when you press Search, and you can ask for the result as a list of books, just the top book, or only how many there are. In the query builder, each field of the form is one where or orderBy, and the Search button is the closing call: get() for the list, first() for the top book, count() for how many.

Sample data

The books table now holds four books: the three from the start, plus The Dancer, made with create() in the Eloquent Basics lesson. The Lab has the same data.

id title author stock
1 The Rainbow Troops Andrea Hirata 3
2 This Earth of Mankind Pramoedya Ananta Toer 0
3 Beauty Is a Wound Eka Kurniawan 2
4 The Dancer Ahmad Tohari 1

where: filtering rows

These are two examples of where. The comments under each query show its SQL, then the books in the result:

$available = Book::where('stock', '>', 0)->get();
// select * from "books" where "stock" > 0
// The Rainbow Troops, Beauty Is a Wound, The Dancer

$outOfStock = Book::where('stock', 0)->get();
// select * from "books" where "stock" = 0
// This Earth of Mankind

This is how the database checks each book for the first condition, stock > 0:

Book stock stock > 0?
The Rainbow Troops 3 yes
This Earth of Mankind 0 no, filtered out
Beauty Is a Wound 2 yes
The Dancer 1 yes

Be careful when you mix where and orWhere. Say you look for books still in stock, by Andrea Hirata or by Pramoedya Ananta Toer:

$wrong = Book::where('stock', '>', 0)
    ->where('author', 'Andrea Hirata')
    ->orWhere('author', 'Pramoedya Ananta Toer')
    ->get();
// ... where "stock" > 0 and "author" = 'Andrea Hirata' or "author" = 'Pramoedya Ananta Toer'
// The Rainbow Troops, This Earth of Mankind

$right = Book::where('stock', '>', 0)
    ->where(fn ($q) => $q->where('author', 'Andrea Hirata')->orWhere('author', 'Pramoedya Ananta Toer'))
    ->get();
// ... where "stock" > 0 and ("author" = 'Andrea Hirata' or "author" = 'Pramoedya Ananta Toer')
// The Rainbow Troops

SQL does and before or. So in $wrong, This Earth of Mankind, with stock 0, is included too: it matches the or condition alone. In $right, the function inside where(...) puts brackets around the two author conditions, so the stock condition applies to both.

orderBy and limit: sorting and capping

This code fetches the books still in stock, sorted from the most copies:

$mostCopies = Book::where('stock', '>', 0)
    ->orderBy('stock', 'desc')
    ->get();
// select * from "books" where "stock" > 0 order by "stock" desc
// The Rainbow Troops (3), Beauty Is a Wound (2), The Dancer (1)

Closing it: get(), first() or count()

Book::where(...) alone sends nothing to the database. Its result only holds the chain of conditions, and the object that holds it is called a Builder. The query is sent when the chain is closed with a closing call:

$favourite = Book::orderBy('stock', 'desc')->first();
// select * from "books" order by "stock" desc limit 1
echo $favourite->title; // The Rainbow Troops

$availableCount = Book::where('stock', '>', 0)->count();
// select count(*) as "aggregate" from "books" where "stock" > 0
echo $availableCount; // 3

$tereLiye = Book::where('author', 'Tere Liye')->get();
echo count($tereLiye); // 0
Closing call Added to the SQL Result When nothing matches
get() (nothing) a Collection of Book objects an empty Collection
first() limit 1 one Book object null
count() select count(*) as "aggregate" a number 0

So the search for Tere Liye books, which aren't in the table, gives an empty Collection, not null and not an error. A foreach over that Collection never runs its body, and its count() is 0. Only first() (and find()) can give null. So check the result of first() before you read a property such as $book->title.

📌 Peeking at the SQL

Swap the closing call for toRawSql() to see the SQL without running it:

echo Book::where('stock', '>', 0)->orderBy('title')->toRawSql();
// select * from "books" where "stock" > 0 order by "title" asc

toSql() shows the version with a ? where each value goes. The values are sent separately from the SQL (these are called bindings). That's what keeps the query builder safe from SQL injection.

⚠️ Builders left open, orders turned around

TL;DR: The query builder is how Eloquent filters, sorts and counts rows without you writing SQL. You chain conditions (call methods one after another, joined with ->), then close the chain. where('column', 'operator', value) filters (two wheres = and), orderBy('column', 'asc') sorts smallest first ('desc' largest first), and limit(n) caps the number of rows. The closing call is what sends the query: get() returns a Collection (empty when nothing matches), first() adds limit 1 and returns one object or null, and count() lets the database count and returns one number. Without a closing call, all you hold is a Builder: a chain of conditions that hasn't been sent. toRawSql() shows the SQL without running it.

⚡ where filters rows

Write:

$available = Book::where('stock', '>', 0)->get();
// The Rainbow Troops, Beauty Is a Wound, The Dancer

Meaning: where filters rows and has three parts: column, operator, value. get() at the end of the line sends the query, and the result is the books with a stock above 0. With only two parts, like where('stock', 0), the operator is taken as = (equals). Two where calls in a row are joined with and: a row must match both.

⚡ orderBy sorts

Write:

$mostCopies = Book::where('stock', '>', 0)
    ->orderBy('stock', 'desc')
    ->get();

Meaning: orderBy('stock', 'desc') sorts the result. 'desc' starts from the biggest number, 'asc' from the smallest. 'asc' is also the default direction, so orderBy('stock') is the same.

⚡ The closing call sends the query

Guess first: Book::where('author', 'Tere Liye')->get(), but there's no Tere Liye book. What comes back?

An empty Collection, whose count() is 0. Not null and not an error. Only first() (and find()) can give null.

Meaning: where and orderBy send nothing until they are closed with a closing call (the last method on the line): get() for a Collection, first() for one object, count() for one number. Without a closing call, all you hold is a Builder, a chain of conditions that hasn't been sent.

In the exercise, the labels must match exactly: Expensive products: and Total products:, colon included.

What you will learn