1

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?

Roi
  • 503
  • 1
  • 12
  • 25
  • 1
    Not when you concatenate/interpolate any of your variables into the query string. If you pass them as parameters in the array, then yes - that's the point of separating the query string from the list of parameters, after all. – Tomalak May 15 '18 at 08:20

1 Answers1

2

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,
     ));
Fahadi Muhumuza
  • 131
  • 1
  • 5
  • What if I'm only using the question mark approach? thanks btw – Roi May 15 '18 at 09:06
  • Not so sure about it yet but you can try this like it has everything you need. [https://www.cubettech.com/blog/laravels-query-builder-and-eloquent-orm/]. And for any other inquiry please ur welcome to ask. – Fahadi Muhumuza May 15 '18 at 10:09