agyanadda@gmail.com

Laravel Query Builder

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 16 of 31

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

Example — Posts per author report PHP
<?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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which is the safe way to put a user value into raw SQL?

Exercise 2 True / False

DB::table('posts')->get() returns Eloquent Post models.

Exercise 3 Fill in the Blank

->___('title', 'id') returns just the titles, keyed by id.

Frequently Asked Questions

Call ->toSql() instead of ->get() to see the SQL with ? placeholders, or ->toRawSql() (newer Laravel versions) to see it with values filled in. Laravel Debugbar or Telescope also show every query a page runs.