I couldn't find it online, but does Eloquent ORM take care of SQL injection like PDO prepared statements do?
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 Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks.
Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all.
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database.
No framework "takes care of" SQL injection.
You take care of SQL injection.
A framework may provide methods of doing that conveniently, but you still have to use the methods consistently.
For example, you should use query parameters instead of concatenating variables into your SQL expressions.
Re your comment:
Eloquent has methods like whereRaw()
which allow you to write any expression you want. Here's an example from the Eloquent docs:
$users = User::whereRaw('age > ? and votes = 100', [25])->get();
If you use this ?
syntax for parameters, and pass the values as the array argument following, then yes, you can safely depend on Eloquent to use parameterization.
But it's not accurate to say "Eloquent takes care of SQL injection" because that leads some naive developers to think that you can do unsafe things like this:
$users = User::whereRaw("age > {$_GET['age']} and votes = 100")->get();
And they mistakenly believe that Eloquent can magically fix it for you. This is not true.
Every ORM provides safe ways of combining application variables into the query, but also provides ways developers can circumvent that. They have to provide those methods, because there are always parts of queries that cannot be parameterized.
That's what I mean when I say it's up to you to use the ORM properly, and avoid unsafe code.
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