Query Builder

Raw Queries and the Fluent Builder

The raw route takes your own SQL: DB::select(), insert(), update() and delete() accept a statement with ? or :name placeholders plus the values, DB::scalar() returns one cell, and DB::statement() runs anything else. The fluent route starts with DB::table('products'), and nothing reaches the server until a terminal method such as get() or pluck() runs.

One question asked in raw SQL and through the fluent builderPHP
$raw = DB::select('select sku from products where stock > ? and price > ?', [5, 43]);
$fluent = DB::table('products')->where('stock', '>', 5)->where('price', '>', 43);
echo $fluent->toSql(), "\n", $fluent->toRawSql(), "\n";
echo json_encode($raw), ' ', $fluent->pluck('sku'), "\n";
Output
select * from `products` where `stock` > ? and `price` > ?
select * from `products` where `stock` > 5 and `price` > 43
[{"sku":"BK-SQL-01"},{"sku":"BK-LAR-01"}] ["BK-SQL-01","BK-LAR-01"]

toSql() shows what PDO prepares; toRawSql() substitutes the bindings for reading only, as the query still travels prepared (Prepared Statements). The raw route returns an array of stdClass rows, the builder a Collection. Use raw SQL for what the builder cannot express, such as a recursive CTE (Recursive CTEs), and the builder for queries assembled from optional parts. DB::unprepared() binds nothing: never pass it input.