Given the example code (Message is an Eloquent model.):
public function submit(Request $request){ $this->validate($request, [ 'name' => "required", "email" => "required" ]); //database connection $message = new Message; $message->name = $request->input("name"); $message->email = $request->input("email"); $message->save(); }
Does Eloquent use parameterized queries (like PDO) or any other mechanisms to prevent SQL injection?
Laravel protects you from SQL injection as long as you're using the Fluent Query Builder or Eloquent. Laravel does this by making prepared statements which are going to escape any user input that may come in through your forms.
In summary, SQL injection is, unfortunately, a thing in Laravel. But validation of user inputs and parameterized queries can help reduce the risk of SQL injection. The security of your Laravel application is a continuous process. And we can't exhaust all the possible vulnerabilities and solutions in a single post.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
Yes, but...
Yes, it does SQL injection prevention when you rely on the built-in ORM functionality, like $someModelInstance->save()
. From the docs:
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.
Please note that you are not automatically protected if you build raw SQL statements and execute those or use raw expressions. More from the docs:
Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.
You should always use parameterized queries when building raw SQL statements or expressions. See the last link above (and other parts of the docs, as wel) for information on how to do that in Laravel/Eloquent.
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