I am junior using Laravel and I would like some advise according to SQL Injections.
I have read that using Eloquent the code is immunized against SQL injections. And I have also read that using built-in Laravel Query Builder does not immunize agasint SQL injections because Query Builder is not Eloquent.
But in the examples on Laravel website, in the Eloquent description, I feel like that they give some examples using Query Builder with Eloquent ?
Could someone help me to understand what's up ? What about security ?
eloquent and query builder both protect you against sql injection, EXCEPT that it is possible to create a RAW sql statement. It is not recommended that you do this, but people do. When they cannot work out the correct query builder methods to do, they will resort to using raw. Raw queries combined with string concatenation are a bad sign.
If you follow any tutorials that suggest using RAW, then I would suggest that there are better tutorials out there.
You are right, most of the queries in Laravel are protected by default but, here are some cases that you need to protect yourself. Here is a common list of mistakes that I was in Laravel code in different projects
Do not pass user-controlled column_name to query builder without whitelisting, this can open an SQL injection
If you have to use DB::raw, make sure data is properly quoted via "DB::getPdo()->quote"
Do not create validation rule based on user-provided data, this also can open an SQL injection flaw
@angelorigo Yes, that code is vulnerable to SQL injection. But you can protect against SQL injection by binding the parameter, which makes Laravel execute the query as a prepared statement:
$query->whereRaw('UPPER(SOME_RANDOM_COLLUMN) LIKE UPPER(?)', [
'%'.$data.'%'
]);
When that SQL statement is prepared, a placeholder is used for the search term instead of the actual value. The search term is never treated as SQL code because it's handled separately from the query structure. The database passes it into the statement as a value when it's executed. This prevents SQL injection.