This question came up in our Slack community, and I liked that this was something they were actively thinking about. It's important to always have security on your mind when building an application.
The specific question was about the whereLike Elqouent method, but it applies equally to any where method using the like operator.
We know Eloquent safely handles query parameters with prepared statements, but how can we be sure this protection extends to LIKE statements?
You could dig through Eloquent's internals, but there is an easier way to be sure.
We can just chain ->toSql() onto the query and see exactly what gets generated.
Here's what I tested, using some potentially dangerous user input:
$userInput = "test'\"%";
User::query()
->where('name', 'like', "%{$userInput}%")
->toSql();
And here's the resulting query:
select * from `users` where `name` like ?
This confirms that Eloquent is using a prepared statement, which is good. With a prepared statement, the user input boundaries are no longer open to interpretation, protecting us from SQL injection.
Here to help,
Joel
P.S. Do you think about security as you're coding? If you want to improve your security mindset, download our free book: 7 Steps to a Secure Laravel App.