Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Secure laravel query which use DB::Raw

I'm really new in Laravel and I'm not sure how can I secure from SQL Injections query which use DB::Raw. I have read trough documentation and I've read that is kind of insecure and should be secured since it's injected in the query as a string...

These expressions will be injected into the query as strings, so be careful not to create any SQL injection points

Myquery looks like this

DB::table('sub_category as sc')
    ->leftJoin('products as p', 'p.sub_cat_id', '=', 'sc.sub_cat_id')
    ->where('sc.category_id', '=', $categoryId)
    ->whereNotNull('p.sub_cat_id')
    ->select('p.*','sc.*', DB::raw('sc.sub_cat_id AS sub_cat_id'))
    ->groupBy('sc.sub_cat_id')
    ->get();

The query simply display on page only categories which have products in it.

like image 931
S.I. Avatar asked Sep 17 '25 22:09

S.I.


1 Answers

The sql injection risk comes -mainly and usually- if there is data sent through $_GET['foo'] or $_POST['bar'] from a web user. You should protect your database from SQL injections by binding data to the raw query as shown:

$risky_input=$_GET['some_risky_input'];//assuming this comes from an input field
$result=
DB::select(
    DB::raw("SELECT * FROM category WHERE category_name=:queriedterm ")
    ,['queriedterm'=>$risky_input]//binds data throuhg array
    )
;

Please notice the colon ":" and variable next to it. This will protect your query from sql injections.

Note: Your query doesn't have any slq injection risk since it doesn't contain parameters from any text input field filled by a web user.

like image 114
alex t Avatar answered Sep 19 '25 12:09

alex t