Skip to main content

What is the query builder?

Laravel’s query builder gives you a fluent, chainable interface for constructing database queries using the DB facade. You start with DB::table() and chain methods until you call a terminal method like get() or first().
Every query uses PDO parameter binding internally, so your application is protected against SQL injection without any extra effort.
The query builder works with all of Laravel’s supported databases: MySQL, MariaDB, PostgreSQL, SQLite, and SQL Server. You can switch databases without rewriting your queries.

When to use the query builder vs. Eloquent

Retrieving data

Fetch all rows

get() returns an Illuminate\Support\Collection of stdClass objects.

Fetch a single row

Pluck a column

Chunk large result sets

Use chunk() when you need to process thousands of rows without loading them all into memory at once:
If you modify records while iterating, use chunkById() instead of chunk(). Updating rows during a chunk() loop can shift offsets and cause records to be skipped.

Stream lazily

lazy() returns a LazyCollection — the query runs in chunks but you iterate over results as a single stream:

Aggregates

Check existence without counting:

Select clauses

Where clauses

Basic conditions

Grouping conditions

Use a closure to wrap OR conditions so they don’t bleed into surrounding AND logic:

Common where helpers

NULL-safe equality

whereNullSafeEquals and orWhereNullSafeEquals compare a column against a value while treating two NULL values as equal. This maps to MySQL’s <=> operator and PostgreSQL’s IS NOT DISTINCT FROM. With a regular = comparison, NULL = NULL evaluates to false. With the NULL-safe variant, it evaluates to true:
Use whereNullSafeEquals when comparing user-provided values that could be null against nullable columns. It avoids the common pitfall where WHERE column = NULL never matches any rows.

Joins

Ordering, grouping, and limiting

Raw expressions

Raw expressions are injected directly into the SQL string. Never pass unvalidated user input to a raw expression — use the bindings array instead.

Insert, update, and delete

Conditional clauses

Apply query constraints only when a condition is true, keeping your code clean:

Debugging

Use toSql() and getBindings() in production-safe debugging. Reserve dd() for local development only — it halts the request.

Quick reference

Last modified on June 21, 2026