What is the query builder?
Laravel’s query builder gives you a fluent, chainable interface for constructing database queries using theDB facade. You start with DB::table() and chain methods until you call a terminal method like get() or first().
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
Usechunk() when you need to process thousands of rows without loading them all into memory at once:
Stream lazily
lazy() returns a LazyCollection — the query runs in chunks but you iterate over results as a single stream:
Aggregates
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.