Raw Queries & When to Use Them
Sometimes the Query Builder or Eloquent can't express complex SQL efficiently. Laravel provides DB::select(), DB::statement(), and raw expressions for these cases. Always use parameter binding to prevent SQL injection.
Raw Query Examples
// Raw select with parameter binding (safe from SQL injection)
$users = DB::select(
'SELECT * FROM users WHERE votes > ? AND status = ?',
[100, 'active']
);
// Raw expression inside Query Builder
DB::table('orders')
->select(DB::raw('DATE(created_at) as date, SUM(total) as revenue'))
->groupBy('date')
->get();
// selectRaw, whereRaw, orderByRaw
DB::table('products')
->selectRaw('price * quantity as total_value')
->whereRaw('price > ? AND stock > 0', [50])
->orderByRaw('FIELD(status, "active", "pending", "archived")')
->get();Tip
Tip
Practice Raw Queries When to Use Them in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Middleware = filters that run before/after your controller logic
Practice Task
Note
Practice Task — (1) Write a working example of Raw Queries When to Use Them 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 Raw Queries When to Use Them is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.