I am trying to create restAPI in Laravel. How can I secure an SQL query like this from sql injection?
Route::get('api/restaurant/id/{id}', 'RestaurantController@getRestaurantById');
public function getRestaurantById($id) {
$restaurant = Restaurant::where('id', $id)->first();
return $restaurant;
}
If you are using laravel ORM to build your sql queries your queries are automatically protected from sql injections.
For example:
$restaurant = Restaurant::where('id', $id)->first();
This query is created by laravel ORM and if you run dd(Restaurant::where('id', $id)->toSql())
you will see that id is not injected in query directly:
SELECT * FROM restaurants WHERE id = ?
You can run sql raw queries using DB::select()
or DB::raw()
... e.t.c.
If you look at laravel documentation you will see that every raw methods has array parameter usually second parameter.
For example:
DB::select('SELECT * FROM restaurants WHERE id = ?', [$id]);
Restaurant::whereRaw('id = ?', [$id])->first();
...
DB::raw('SELECT * FROM restaurants WHERE id = ?', [$id]);
Each of above queries are safe from sql injections.
Do not write queries like this
DB::select("SELECT * FROM restaurants WHERE id = $id");
This can be extremly dangerous for your app.
For more information look at here: https://laravel.com/docs/5.8/database#running-queries
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With