1

I am currently implementing search functionality in my Laravel 5 application. Right now I have the following code:

$terms = implode("* ", explode(" ", trim($query)." "));
$sql = "MATCH(title, content) AGAINST('".$terms."' IN BOOLEAN MODE)";
$results = Post::whereRaw($sql);

Where $query is a user-supplied string. The code takes (space-separated) keywords from the users and runs a full text search on them. The problem is that a simple ' can break the SQL query and allows for SQL injection. What would be the best way to prevent this?

Streetlamp
  • 1,537
  • 2
  • 15
  • 27
  • http://laravel.com/docs/4.2/queries – Marc B Jul 27 '15 at 21:48
  • @MarcB I looked at the documentation, but was unable to find a native implementation of the `MATCH ... AGAINST ...` syntax. Did I overlook something? – Streetlamp Jul 27 '15 at 21:49
  • 1
    possible duplicate of [Escape raw SQL queries in Laravel 4](http://stackoverflow.com/questions/18951057/escape-raw-sql-queries-in-laravel-4) – Iłya Bursov Jul 27 '15 at 22:03
  • @Lashane I would argue that the answer provided here is more elegant than the one posted in the question you linked. This is probably because the solution provided below did not exist in Laravel 4. I think that this question provides a solution that will be helpful to future users of Laravel 5. – Streetlamp Jul 27 '15 at 22:10

1 Answers1

0

You can use PDO bindings with the whereRaw and that will take care of escaping the passed parameters:

$terms = implode("* ", explode(" ", trim($query)." "));
$sql = "MATCH(title, content) AGAINST(? IN BOOLEAN MODE)";
$results = Post::whereRaw($sql, [$terms]);
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • Thank you, this seems to work, only problem is that I can no longer view the query to debug. Does Laravel internally add `'` around the `?` (=`$terms`)? – Streetlamp Jul 27 '15 at 21:54
  • Yes it does. Laravel uses [PDO](http://php.net/manual/en/book.pdo.php) to create prepared statements, so you're safe. – Bogdan Jul 27 '15 at 21:55
  • From my experience, Laravel does not actually add the `'` around the input when constructing the SQL. Could you update your answer to include the quotation marks for any future users seeing this question? – Streetlamp Jul 29 '15 at 00:55