Jesper Andersen
Jesper Andersen

Reputation: 574

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?

Upvotes: 24

Views: 106440

Answers (3)

Jay Patel
Jay Patel

Reputation: 1

public function addsubEmployee(Request $reqest){

    Sub_employee::create([
        "se_name"=> $reqest->se_name,
    ]);

    return redirect()->route("subEmployee");
}

Upvotes: -3

Bogdan Koliesnik
Bogdan Koliesnik

Reputation: 900

  • 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.

Upvotes: 72

Yan Zhao
Yan Zhao

Reputation: 469

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.

Upvotes: 3

Related Questions