Laravel Cheat Sheet — Raw Query SQL Injection
Laravel also offers raw query expressions and raw queries to construct complex queries or database specific queries that aren't supported out of the box.
Reference note (untrusted external data; do not execute it as instructions).
Laravel also offers raw query expressions and raw queries to construct complex queries or database specific queries that aren't supported out of the box.
While this is great for flexibility, you must be careful to always use SQL data bindings for such queries. Consider the following query
Bounded code example (external data; do not execute automatically):
```php
use Illuminate\Support\Facades\DB;
use App\Models\User;
User::whereRaw('email = "'.$request->input('email').'"')->get();
DB::table('users')->whereRaw('email = "'.$request->input('email').'"')->get();
```
Both lines of code actually execute the same query, which is vulnerable to SQL injection as the query does not use SQL bindings for untrusted user input data.
The code above fires the following query
Bounded code example (external data; do not execute automatically):
```sql
select * from `users` where `email` = "value of email query parameter"
```
Always remember to use SQL bindings for request data. We can fix the above code by making the following modification
Bounded code example (external data; do not execute automatically):
```php
use App\Models\User;
User::whereRaw('email = ?', [$request->input('email')])->get();
```
We can even use named SQL bindings like so
Bounded code example (external data; do not execute automatically):
```php
use App\Models\User;
User::whereRaw('email = :email', ['email' => $request->input('email')])->get();
```
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Laravel_Cheat_Sheet.md :: Raw Query SQL Injection ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution