Query Builder — Fluent Database Queries
The Query Builder provides a fluent interface for building SQL queries without writing raw SQL. It works directly on database tables (not models) and supports selects, joins, aggregates, inserts, updates, and deletes with full SQL injection protection.
Query Builder Examples
use Illuminate\Support\Facades\DB;
// Select
$users = DB::table('users')->get(); // All rows
$user = DB::table('users')->where('id', 1)->first(); // Single row
$emails = DB::table('users')->pluck('email'); // Single column
// Filtering
DB::table('posts')
->where('published', true)
->where('views', '>', 100)
->orWhere('featured', true)
->whereBetween('created_at', [$start, $end])
->whereIn('category_id', [1, 2, 3])
->whereNotNull('published_at')
->orderBy('created_at', 'desc')
->limit(10)
->get();
// Aggregates
DB::table('orders')->count();
DB::table('orders')->sum('total');
DB::table('orders')->avg('total');
DB::table('orders')->max('total');
// Joins
DB::table('posts')
->join('users', 'posts.user_id', '=', 'users.id')
->select('posts.*', 'users.name as author')
->get();
// Insert, Update, Delete
DB::table('posts')->insert(['title' => 'New Post', 'body' => '...']);
DB::table('posts')->where('id', 1)->update(['title' => 'Updated']);
DB::table('posts')->where('id', 1)->delete();Tip
Tip
Practice Query Builder Fluent Database Queries in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Eloquent for 90% of queries. Query Builder for reports. Raw SQL rarely needed.
Practice Task
Note
Practice Task — (1) Write a working example of Query Builder Fluent Database Queries from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Query Builder Fluent Database Queries is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.