Yes laravel provide defense against sql injection.
This is because since the query builder is using PDO in the background, we know there is a way to bind parameters to our query so it will sanitize the bound variables.
Now, as you've seen, arbitrary (raw) queries are done in the query builder using the for example DB::select()
method. Let's look at the select()
method in Illuminate\Database\Connection
to see if it has any way to bind our parameters. Let us dive into it:
public function select($query, $bindings = [], $useReadPdo = true)
{
return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
if ($this->pretending()) {
return [];
}
// For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $this->prepared($this->getPdoForSelect($useReadPdo)
->prepare($query));
$this->bindValues($statement, $this->prepareBindings($bindings));
$statement->execute();
return $statement->fetchAll();
});
}
And your query can look like this:
$someVariable = Input::get("some_variable");
DB::select("SELECT * FROM some_table WHERE some_col = :somevariable", array(
'somevariable' => $someVariable,
));