The Query Builder (DB::table()) writes SQL for you without models. It is useful for reports, joins and quick queries. It uses prepared statements, so values are safe from SQL injection.
Reading
DB::table('posts')->get()— all rows (plain objects)->where('views', '>', 100),->orWhere(...),->whereIn('id', [1, 2, 3])->whereNull('deleted_at'),->whereBetween('price', [100, 500])->orderBy('created_at', 'desc'),->limit(10)->first(),->value('title'),->pluck('title', 'id')
Aggregates
count(), sum('amount'), avg('rating'), max('price'), min('price').
Joins and grouping
->join('users', 'users.id', '=', 'posts.user_id'), ->groupBy('user_id'), ->selectRaw('COUNT(*) as total').
Writing
insert([...]), update([...]), delete() and increment('views').
Raw SQL safely
DB::select('select * from users where email = ?', [$email]) — always pass values as bindings (?), never by joining strings into the SQL.
Eloquent or Query Builder? Use Eloquent for normal app code (relationships, events, casts). Use the Query Builder for heavy reports and bulk updates.
Example
<?php
use Illuminate\Support\Facades\DB;
$report = DB::table('posts')
->join('users', 'users.id', '=', 'posts.user_id')
->select('users.name', DB::raw('COUNT(posts.id) as total'))
->where('posts.is_published', true)
->groupBy('users.id', 'users.name')
->orderByDesc('total')
->get();
foreach ($report as $row) {
echo "$row->name: $row->total posts" . PHP_EOL;
}
// Bulk update in one query
DB::table('posts')->where('user_id', 7)->update(['is_published' => false]);
Output, e.g.: "Asha: 12 posts", "Ravi: 8 posts". The join and GROUP BY run as one SQL query.