Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I secure this sql query from SQL Injection in Laravel?

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;
    }
like image 816
Dominik Balogh Avatar asked Jan 25 '23 07:01

Dominik Balogh


1 Answers

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.

like image 195
Malkhazi Dartsmelidze Avatar answered Jan 28 '23 09:01

Malkhazi Dartsmelidze