0
0
LaravelHow-ToBeginner · 4 min read

How to Use Raw Query in Eloquent in Laravel

You can run raw SQL queries in Eloquent using the DB::select() method for SELECT statements or DB::statement() for other queries. Use parameter binding with ? placeholders to safely insert variables and avoid SQL injection.
📐

Syntax

Laravel provides the DB facade to run raw SQL queries. The main methods are:

  • DB::select($query, $bindings) - runs a SELECT query and returns results.
  • DB::statement($query, $bindings) - runs any SQL statement like INSERT, UPDATE, DELETE.

Use ? as placeholders in the query and pass an array of values as $bindings to safely insert variables.

php
use Illuminate\Support\Facades\DB;

// Raw select query
$users = DB::select('SELECT * FROM users WHERE active = ?', [1]);

// Raw insert/update/delete
DB::statement('UPDATE users SET votes = votes + 1 WHERE id = ?', [10]);
💻

Example

This example shows how to fetch active users using a raw query with parameter binding to avoid SQL injection.

php
<?php
use Illuminate\Support\Facades\DB;

Route::get('/active-users', function () {
    $activeUsers = DB::select('SELECT id, name, email FROM users WHERE active = ?', [1]);
    return response()->json($activeUsers);
});
Output
[{"id":1,"name":"Alice","email":"alice@example.com"},{"id":3,"name":"Bob","email":"bob@example.com"}]
⚠️

Common Pitfalls

Common mistakes when using raw queries in Eloquent include:

  • Not using parameter binding, which risks SQL injection.
  • Using raw queries when Eloquent or Query Builder can do the job more safely and cleanly.
  • Forgetting to import the DB facade.

Always prefer parameter binding over string concatenation.

php
use Illuminate\Support\Facades\DB;

// Wrong: vulnerable to SQL injection
$userId = 1;
$users = DB::select("SELECT * FROM users WHERE id = $userId");

// Right: safe with parameter binding
$users = DB::select('SELECT * FROM users WHERE id = ?', [$userId]);
📊

Quick Reference

MethodPurposeExample Usage
DB::selectRun SELECT queries and get resultsDB::select('SELECT * FROM users WHERE id = ?', [1])
DB::statementRun INSERT, UPDATE, DELETE, or other SQL statementsDB::statement('UPDATE users SET active = 1 WHERE id = ?', [1])
Parameter BindingSafely insert variables to prevent SQL injectionDB::select('SELECT * FROM users WHERE email = ?', [$email])

Key Takeaways

Use DB::select() for raw SELECT queries and DB::statement() for other SQL commands.
Always use parameter binding with ? placeholders to avoid SQL injection.
Raw queries bypass Eloquent features, so use them only when necessary.
Import the DB facade before using raw queries.
Prefer Eloquent or Query Builder for readability and safety when possible.