devnotes.

Query Builder & Raw SQL

When you need database access without a full Eloquent model — or want finer control — Laravel's query builder (via the DB facade) provides a fluent, database-agnostic interface.

use Illuminate\Support\Facades\DB;

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

$total = DB::table('orders')
    ->join('users', 'users.id', '=', 'orders.user_id')
    ->where('orders.status', 'completed')
    ->sum('orders.total');

DB::table('posts')->insert(['title' => 'New post', 'body' => '...']);
DB::table('posts')->where('id', 1)->update(['published' => true]);
DB::table('posts')->where('id', 1)->delete();

For complex reporting queries, raw expressions are supported: DB::raw('COUNT(*) as total'), and parameterized raw queries via DB::select('SELECT * FROM posts WHERE user_id = ?', [$id]) — always use bindings (? or named parameters) rather than string-concatenating user input, to avoid SQL injection.

Transactions wrap multiple queries so they either all succeed or all roll back together:

DB::transaction(function () {
    DB::table('accounts')->where('id', 1)->decrement('balance', 100);
    DB::table('accounts')->where('id', 2)->increment('balance', 100);
});
Laravel Query Builder and Transactions | DevNotes