Francisunoxx
Francisunoxx

Reputation: 1458

How to use Prepared Statement in Laravel 5.2

I created a simple insert statement in Laravel 5.2 like these.

User::create([
        'email' => $request->input('email'),
        'username' => $request->input('username'),
        'password' => bcrypt($request->input('password')),
    ]);

But I want my database more secure so I prefer using Prepared Statement. I'm asking to properly write the syntax? How can I properly hash my password within statement?

User::insert('insert into users (email, username, password) values (?,?,?)');

Upvotes: 2

Views: 19028

Answers (1)

Sasa Blagojevic
Sasa Blagojevic

Reputation: 2200

Eloquent does that for you behind the scenes, after doing all its fancy stuff, in the end, Eloquent calls PDO::prepare(), PDO::bindValue() and finally PDO::execute();.

Go through the code of Illuminate\Database\Connection to get the gist of it.

The only thing you need to be careful about is not to use DB::raw() with directly provided user input, for example:

// This is bad
DB::raw('SELECT * FROM table_name WHERE col = '.$request->query('col'));

// This is good
DB::raw('SELECT * FROM table_name WHERE col = ?', [$request->query('col')]);
//or
DB::raw('SELECT * FROM table_name WHERE col = :col', ['col' => $request->query('col')]);

Upvotes: 10

Related Questions