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

3

23

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?

Axum answered 24/8, 2016 at 9:7 Comment(0)
D
69
  • 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.

Dell answered 24/8, 2016 at 9:17 Comment(3)
That's what I figured it was. But is any prefered compared to the other? For example, I didn't know how to use "insert ignore" with Query Builder, so I chose raw sql. So are there any pros and cons to consider when using either of them?Axum
You've answered your question. Query builder is for most common cases, if you need some specific - use raw query. There ar no pros and cons, they do same thing in different ways. Query builder is more convinient and readable - that's all.Dell
Hi, after running a DB::insert() the next PDO prepared statement complains with the following error: > [2017-06-08 03:04:41] local.ERROR: PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. Is there a command that needs to be run after every DB::insert() ? ThanksGarrott
B
3

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.

Belita answered 1/11, 2018 at 1:51 Comment(0)
Q
-3

public function addsubEmployee(Request $reqest){

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

    return redirect()->route("subEmployee");
}
Quarterstaff answered 31/1, 2023 at 8:5 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Pruinose

© 2022 - 2024 — McMap. All rights reserved.