24

In my controller I have this code:

public function create($brand_id)
{
    Brand::findOrFail($brand_id);
}

and this:

public function search() 
{
    $q = Input::get('q');
    $brands = Brand::where('title', 'LIKE', '%'.$q.'%')->take(80)->get();

Is this code safe? By "safe" I mean SQL injection safe. Or should I do some variable clean up here? And what is the best way for cleaning up user input? Thanks a lot for helping me :)

gustavgans
  • 5,141
  • 13
  • 41
  • 51

3 Answers3

35

yes Eloquent uses parameter binding behind the scene, which safely escapes any input used in where().

Julio Feferman
  • 2,658
  • 3
  • 15
  • 26
Master Bee
  • 1,089
  • 1
  • 12
  • 18
  • 1
    I tested this myself... I don't think this is correct – Okiemute Omuta Dec 11 '14 at 14:54
  • 4
    @OkiemuteOmuta Well if it is not safe can you provide an example? because documentation states: Note: The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings. – Dusan Plavak Jan 17 '15 at 04:09
  • 1
    Exacly, Laravel provides protection for injection out of box if you are using either Eloquent or query builder. It is quite interesting why you think it is not correct. – Maksym Mar 16 '15 at 14:40
  • 11
    But it doesn't protect you when using raw statements withing a query builder. – Jin Jul 27 '17 at 14:21
6

Document says that Eloquent handles this behind the scene but you can also use like DB::escape($q) to be in safer side

Robert
  • 5,278
  • 43
  • 65
  • 115
1

Yes but note not all parameters are safe in the where statement:

public function search() 
{
  $col = Input::get('col');
  $brands = Brand::where($col, 'LIKE', '%sql injection in column name%')->take(80)->get();

In this case sql injection is possible!

The first parameter: the column name is not validated or checked and sql injection is possible here, make sure you protect this properly yourself!

Joel Harkes
  • 10,975
  • 3
  • 46
  • 65