Is orderBy() method in Laravel provides protection against sql injection?
Ex:
$column = "SUBSTRING_INDEX(material_type, '\\\', -1)";
$sort = 'desc';
DB::table('students')->orderBy(DB::raw($column), $sort)->get();
Is orderBy() method in Laravel provides protection against sql injection?
Ex:
$column = "SUBSTRING_INDEX(material_type, '\\\', -1)";
$sort = 'desc';
DB::table('students')->orderBy(DB::raw($column), $sort)->get();
->orderBy(DB::raw($column), $sort)
is not secure, raw expressions are always vulnerable to SQL injections.
You can use ->orderBy($column, $sort)
, but I wouldn't recommend it.
Laravel does not use parameter binding for column names because the underlying PDO
doesn't support it (reference). Parameter bindings can only be used for values (where name = ?
).
Laravel tries to prevent SQL injections through the column name (reference), but I wouldn't rely on that. I assume you have a list of allowed column names, so use it as a whitelist:
$columns = ['id', 'name', 'created_at', ...];
if(!in_array($column, $columns, true)) {
// Throw an exception or set $column to a secure default value.
}
Laravel uses asc
as the default direction if the provided value is invalid (reference).
So I would say that you don't have to check $sort
yourself.
In Short, YES.
Modify your code from
DB::table('students')->orderby(DB::raw($column), $sort);
to
DB::table('students')->orderBy($column, $sort);
Why?
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
If you use DB::raw($text)
then no. what is inside $text
goes into the query as is.
As suggested, use:
DB::table('students')->orderby($column, $sort);
in this case, yes the orderBy()
method in Laravel provides protection against sql injection since the variables will be passed as bindings.
PS: it's the same case for all methods of eloquent. if you use DB::raw()
you need to be extra careful.