Search code examples
phpmysqlsqllaravelsql-injection

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;
    }

Solution

  • Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

    The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings. introduction

    Please note that you are not automatically protected if you build raw SQL statements and execute those or use raw expressions.