Search code examples
laravelsql-injection

prevent sql injection in laravel


Suppose using raw query I have the following in laravel

$a = DB::select( DB::raw("SELECT * FROM table WHERE col = '$var'") );

How can I protect our application from SQL injection attacks in this type of cases?


Solution

  • select() method in Illuminate\Database\Connection has a way to bind our parameters:

    public function select($query, $bindings = array())
    {
        ....
        ....
    }
    

    so we can pass an array of bindings to the select() method

    so

    $a = DB::select( DB::raw("SELECT * FROM table WHERE col = :var") , array(
       'var' => $var,
     ));