Laravel Query Builder: Complete Guide + Examples 2026

When building an application with Laravel, you don't always have to use the Eloquent ORM. For more complex queries, or when performance becomes a priority, the Query Builder is the...

Laravel Query Builder: Complete Guide + Examples 2026
Advertisement

When building an application with Laravel, you don't always have to use the Eloquent ORM. For more complex queries, or when performance becomes a priority, the Query Builder is the right choice. The Query Builder provides a convenient and secure interface for building SQL queries without writing raw SQL directly.

What Is the Query Builder?

The Query Builder is an abstraction layer on top of PDO that Laravel provides through the DB facade. With the Query Builder, you can build queries through method chaining, and Laravel automatically handles data escaping so you are protected from SQL Injection.

Retrieving Data (Select)

The most basic approach is retrieving all rows from a table:

Advertisement
use Illuminate\Support\Facades\DB;

// Get all data from the users table
$users = DB::table('users')->get();

// Get only specific columns
$users = DB::table('users')->select('name', 'email')->get();

// Get the first matching row
$user = DB::table('users')->where('email', 'john@example.com')->first();

// Get the value of a single column
$email = DB::table('users')->where('id', 1)->value('email');

Filtering with Where

The Query Builder provides many variations of the where method to filter data:

// Basic where
$users = DB::table('users')->where('status', 'active')->get();

// Where with an operator
$users = DB::table('users')->where('age', '>=', 18)->get();

// Multiple where (AND)
$users = DB::table('users')
    ->where('status', 'active')
    ->where('role', 'admin')
    ->get();

// Where OR
$users = DB::table('users')
    ->where('role', 'admin')
    ->orWhere('role', 'editor')
    ->get();

// Where IN
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();

// Where NULL
$users = DB::table('users')->whereNull('deleted_at')->get();

// Where Between
$orders = DB::table('orders')
    ->whereBetween('created_at', ['2024-01-01', '2024-12-31'])
    ->get();

Insert, Update, and Delete

The Query Builder also supports write operations to the database:

// Insert a single row
DB::table('products')->insert([
    'name'       => 'Gaming Laptop',
    'price'      => 15000000,
    'created_at' => now(),
    'updated_at' => now(),
]);

// Insert and get the newly created ID
$id = DB::table('products')->insertGetId([
    'name'  => '4K Monitor',
    'price' => 5000000,
]);

// Update data
DB::table('products')
    ->where('id', $id)
    ->update(['price' => 4500000]);

// Increment/Decrement a numeric column
DB::table('products')->where('id', 1)->increment('stock', 10);
DB::table('products')->where('id', 1)->decrement('stock', 2);

// Delete
DB::table('products')->where('id', $id)->delete();

Joining Tables

The Query Builder supports various types of JOIN to combine multiple tables:

$orders = DB::table('orders')
    ->join('users', 'orders.user_id', '=', 'users.id')
    ->join('products', 'orders.product_id', '=', 'products.id')
    ->select(
        'orders.id',
        'users.name as customer_name',
        'products.name as product_name',
        'orders.total'
    )
    ->where('orders.status', 'completed')
    ->orderBy('orders.created_at', 'desc')
    ->get();

Aggregation and Grouping

For reporting needs, the Query Builder provides aggregate functions:

Advertisement
// Count the total rows
$count = DB::table('users')->where('status', 'active')->count();

// Sum, average, min, max
$total   = DB::table('orders')->sum('total');
$average = DB::table('orders')->avg('total');
$max     = DB::table('orders')->max('total');

// Group By with having
$summary = DB::table('orders')
    ->select('user_id', DB::raw('SUM(total) as total_belanja'))
    ->groupBy('user_id')
    ->having('total_belanja', '>', 500000)
    ->get();

Pagination and Limit

Limiting and paginating query results is very easy:

// Manual limit and offset
$users = DB::table('users')->limit(10)->offset(20)->get();

// Laravel's automatic pagination
$users = DB::table('users')->paginate(15);

// Simple pagination (prev/next only)
$users = DB::table('users')->simplePaginate(15);

Raw Expressions

When you need a special SQL expression that the Query Builder doesn't support directly, use DB::raw():

$users = DB::table('users')
    ->select(DB::raw('COUNT(*) as total, status'))
    ->groupBy('status')
    ->get();

// whereRaw for raw SQL conditions
$users = DB::table('users')
    ->whereRaw('YEAR(created_at) = ?', [2024])
    ->get();

Conclusion

The Laravel Query Builder is an incredibly powerful tool for interacting with your database flexibly. With intuitive method chaining, you can build complex queries ranging from select, join, and aggregation to insert and update — all with automatic protection against SQL Injection. Use the Query Builder when you need full control over your query without the overhead of Eloquent, especially for reporting queries or queries that involve many tables.

Advertisement
query builder laravel laravel database query DB facade laravel query builder php laravel select where query database laravel
Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →
Advertisement
Advertisement