Search code examples
phplaravelpdoeloquentsql-injection

Is it safe to pass form request directly to model in Laravel/Eloquent?


I'm using Laravel/Eloquent outside of the the laravel..

for some user scenarios i need to write my own Validation Class since I'm not using all the Laravel components..

So my question is: should I care sql injection in my Validation Class?..In other words is the following piece of code already safe?

//$user is an instance from a User Class extends Eloquent..
$user->username = $_REQUEST['username'];

Solution

  • Yes, this is save, in this case you don't have to worry about SQL injection. Finally this method is executed:

    https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Query/Builder.php#L1819

    and as you see there are bindings here. The same bibndings are used in https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/ConnectionInterface.php

    Finally this method:

    https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Connection.php#L381

    will be executed - this is PDO prepared statement so as you see you should not worry about SQL injection.

    Of course I always recommend validating data to make sure you are getting what you expect. You probably don't want in username characters like %, ^ etc so you should use validation no matter of SQL injection