skip to Main Content

I have codes see below which is works.

$city = City::find(1);
$city->location = DB::raw('geomfromtext('point(' . $location . ')')');
$city->save();

Question 1:
Is there SQL injection issue in the codes above because I using DB::raw() which sticking the string(variable) in without processing ?

Question 2:
If yes, there is SQL injection issue in the codes, how to bind the variables into DB::raw()?

Thanks

I tried below.

DB::connection('datadb')->table('city')->where('id', '=', $profile->id)->update(['location' => DB::raw("(GEOMFROMTEXT('POINT(54.8765696 -2.9261824)'))")]);

It works, but if I try to do like below. It failed.

$location = ‘54.8765696 -2.9261824’;
DB::connection(‘datadb’)->table(‘city’)->setBindings([$location, $profile->id])->whereRaw(‘id = ?’)->update([‘location’ => DB::raw("(GEOMFROMTEXT(‘POINT(?)’))")]);

I got the error "SQLSTATE[HY093]: Invalid parameter number (Connection: datadb, SQL: update city set location = (GEOMFROMTEXT(‘POINT(-33.742612777347 151.27899169922)’)) where id = 1126)""

But the query "update city set location = (GEOMFROMTEXT(‘POINT(-33.742612777347 151.27899169922)’)) where id = 1126;" definitely works.

2

Answers


    1. Laravel’s orm(eloquent) prevents sql injections, but not with raw()
    2. $city->location = DB::raw(‘geomfromtext(‘point(‘:location’)’)’, [‘location ‘ => $location]); is how you bind variables in eloquent
    Login or Signup to reply.
  1. What docs say about raw expressions/methods:

    Raw statements will be injected into the query as strings, so you should be extremely careful to avoid creating SQL injection vulnerabilities.

    and

    Laravel can not guarantee that any query using raw expressions is protected against SQL injection vulnerabilities.

    A tip is that you can pass an array of bindings to most raw query methods to avoid SQL injection.:

    // This is vulnerable to SQL injection
    $fullname = request('full_name');
    User::whereRaw("CONCAT(first_name, last_name) = $fullName")->get();
    
    // Use bindings
    User::whereRaw("CONCAT(first_name, last_name) = ?", [request('full_name')])->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search