Escape raw SQL queries in Laravel 4

48,925

Solution 1

You can quote your strings this way, through the DB facade.

DB::connection()->getPdo()->quote("string to quote");

I did put this answer in my question when I discovered it, however I've now put it in as an actual answer to make it easier for others to find.

Solution 2

$value = Input::get("userID");

$results = DB::select( DB::raw("SELECT * FROM users WHERE users.id = :value"), array(
   'value' => $value,
 ));

More Details HERE

Solution 3

You may also try this, (Read Documentation)

$results = DB::select('SELECT * FROM users WHERE users.id = ?', array($userId));

Solution 4

I found this question when looking for generic sql escaping in Laravel. What I actually needed though was table/column name escaping. So, for future reference:

/**
 * Quotes database identifier, e.g. table name or column name. 
 * For instance:
 * tablename -> `tablename`
 * @param  string $field 
 * @return string      
 */
function db_quote_identifier($field) {
  static $grammar = false;
  if (!$grammar) {
    $grammar = DB::table('x')->getGrammar(); // The table name doesn't matter.
  }
  return $grammar->wrap($field);
}

Solution 5

Two answers here, that I use, have less verbose solutions built into the DB facade.

First, value quoting:

// From linked answer
DB::connection()->getPdo()->quote("string to quote");
// In the DB facade
DB::getPdo()->quote('string to quote');

Second, identifier quoting (table and column names):

// From linked answer
DB::table('x')->getGrammar()->wrap('table.column');
// In the DB facade
DB::getQueryGrammar()->wrap('table.column');
Share:
48,925
Dwight
Author by

Dwight

Updated on June 27, 2020

Comments

  • Dwight
    Dwight almost 4 years

    How does one go about escaping parameters passed to a raw query in Laravel 4? I expected something like DB::escape() (which rings a bell from Laravel 3) and also attempted DB::quote() (which I thought could be available through the PDO object)

    $query = DB::select("SELECT * FROM users WHERE users.id = " . DB::escape($userId));
    

    We can't use the select method with placeholders as the above is just a simplified example of what we are trying to achieve. We have a large custom query with a few nested select queries that cannot be adapted to the query builder.

    What is the best approach to escaping something prior to inserting in Laravel 4?

    EDIT:

    I've just discovered that you can access the PDO object and use the quote function on it this way. Is this still the best approach, or is there an easier way to access this function?

    DB::connection()->getPdo()->quote("string to quote");