Fix SQL Injection (Legacy & Modern) in Laravel
SQLi in Laravel is not extinct; it has evolved. While Eloquent provides a layer of protection, developers frequently bypass it using raw expressions like DB::raw(), whereRaw(), or orderByRaw(). If you are concatenating user-controlled input into these methods, your application is wide open. A Senior Researcher knows that the ORM is only as secure as the developer's refusal to write raw strings.
The Vulnerable Pattern
// VULNERABLE: Direct string interpolation in raw queries $id = $request->input('id'); $user = DB::select("SELECT * FROM users WHERE id = " . $id);
// VULNERABLE: Modern Laravel raw expression bypass $sortBy = $request->input(‘sort’); // Attacker sends ‘id; DROP TABLE users;’ $users = User::where(‘active’, 1)->orderByRaw($sortBy)->get();
The Secure Implementation
The core of the fix is ensuring that data is never interpreted as command logic. Laravel's underlying PDO implementation uses prepared statements which separate the SQL template from the data. When using raw methods, you must pass user input as a separate array of bindings. For structural elements like column names or 'ORDER BY' clauses which cannot be bound, you must implement strict allow-listing (validation against a hardcoded set of permitted values) to prevent second-order injection or syntax manipulation.
// SECURE: Using positional parameter bindings $id = $request->input('id'); $user = DB::select("SELECT * FROM users WHERE id = ?", [$id]);// SECURE: Using named parameter bindings in Eloquent $users = User::whereRaw(“name = :name”, [‘name’ => $request->input(‘name’)])->get();
// SECURE: Strict allow-listing for dynamic column names $allowedSorts = [‘id’, ‘created_at’, ‘price’]; $sortBy = in_array($request->input(‘sort’), $allowedSorts) ? $request->input(‘sort’) : ‘id’; $users = User::orderBy($sortBy)->get();
Your Laravel API
might be exposed to SQL Injection (Legacy & Modern)
74% of Laravel apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.