Roi
Roi

Reputation: 565

Does Laravel naturally prevent SQL injection when using raw SQL?

I know everyone is using DB::raw() to execute a raw sql.

I myself use the following instead:

DB::select("query string?", [$var]);
DB::insert("query string?", [$var]);
DB::update("query string?", [$var]);
DB::delete("query string?", [$var]);

does Laravel already provide defense against SQL injection or I still need to escape my variables?

Upvotes: 3

Views: 4041

Answers (1)

Fahadi Muhumuza
Fahadi Muhumuza

Reputation: 161

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,
     ));

Upvotes: 4

Related Questions