Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Laravel DB::insert() and DB::table()->insert()

I've been trying to figure out which one to use when, and if I should even use both.

Been looking at Laravel docs and they have both in there. From what I can make out of it, DB::insert() provides more "tailored" query than DB::table()->insert() does.

Would anyone be able to clarify what exactly the difference is in the two when it comes to how and when to use which?

like image 920
Jesper Andersen Avatar asked Aug 24 '16 09:08

Jesper Andersen


2 Answers

  • DB::insert() for raw sql queries. Example:

    DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

  • DB::table()->insert() for query builder. Example:

    DB::table('users')->insert( ['email' => '[email protected]', 'votes' => 0] );

Query builder compiles conditions to raw sql query, but I am using it because it is much more convenient.

like image 108
Bogdan Koliesnik Avatar answered Nov 11 '22 11:11

Bogdan Koliesnik


You always try to use query builder as much as possible, it prevents SQL injection.

The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings

Query Builder also helps with special chars such as ', " in values. For raw statement, you need to take care of the special chars yourself.

like image 21
Yan Zhao Avatar answered Nov 11 '22 12:11

Yan Zhao