I'm building an application with Laravel 5.5 and I have to run some SQL queries for extended PostgreSQL which are not supported by Eloquent ORM (PostGIS). Instead, I use DB::statement($queryString); to insert data into database. $queryString is built from input variables concatenated with pre-built SQL statement.
Here is the code from my controler (note that actual query is more complex, this is just an example):
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$id= $request->input('id');
$name= $request->input('name');
$geom = $request->input('geom');
$geom = DB::raw("ST_TRANSFORM(ST_GeomFromGeoJSON('".$geom."'), 3857)");
$statement = "INSERT INTO tableName(id, name) VALUES ('".$id."', '".$name."', ".$geom.");";
DB::statement($statement);
return 'Insert Successful';
}
I have two question about this approach:
How can I protect my application from SQL injection attacks?
How can I check if query ran successfully? DB::statement doesn't seem to return anything.