问题
I couldn't find it online, but does Eloquent ORM take care of SQL injection like PDO prepared statements do?
回答1:
As per your question all the eloquent queries are taken care of for SQL injection, because they use the PDO driver in core. So you don't have to worry, but the input are stored as they are so you might want to sanitize as per your application's needs (HTML formatting, etc.)
回答2:
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.
回答3:
Yes but the onus is still on you to validate the data coming in, and escape data coming out, as prepared statements are only part of the picture.
As a side note - I don't think dependency injection means what you think it means. Laravel does dependency injection via its service container, but DI is actually a good thing (https://en.wikipedia.org/wiki/Dependency_injection)
来源:https://stackoverflow.com/questions/41539095/does-eloquent-ormlaravel-5-take-care-of-sql-injection