Eloquent create() VS Query Builder insert() Method

To add a record to the database, you may use one of two methods:

1$product = [
2 'name' => 'Some product',
3 'price' => 123,
4 'stock_left' => 999
5];
6 
7// You can use Eloquent
8Product::create($product); // don't forget to fill $fillable in Model
9 
10// Or you can use Query Builder:
11Product::insert($product);

There are a few differences.


Difference 1. Return Model vs Boolean

Here are the results of the queries above:

1// Returned after Product::create():
2
3App\Models\Product {#3866
4 name: "Some product",
5 price: 123,
6 stock_left: 999,
7 updated_at: "2023-01-07 08:38:02",
8 created_at: "2023-01-07 08:38:02",
9 id: 6,
10}
11
12// Returned after Product::insert():
13
14true

So the insert() method returns just true/false, depending on whether the statement was successful or not.


Difference 2. Autofill Timestamps and Other Eloquent "Magic"

If you launch Product::create(), it will auto-fill the fields of created_at and updated_at, because it's Eloquent behavior.

If you launch Product::insert(), it comes from the Query Builder, so your timestamps will be NULL.

Eloquent create Query Builder insert

Following the same logic, insert() wouldn't trigger any of the Eloquent features:

  • Accessors/mutators
  • Observers
  • Events/listeners
  • Traits

In other words, the insert() is literally a query to the database, that's it. Almost like a raw SQL query.


Difference 3. Multiple Inserts

If you want to add multiple records at once, you can do it with insert() but not with create().

Imagine this:

1$products = [
2 [
3 'name' => 'Some product',
4 'price' => 123,
5 'stock_left' => 999
6 ],
7 [
8 'name' => 'Other product',
9 'price' => 456,
10 'stock_left' => 9999
11 ],
12 
13 // ... more products
14];
15 
16// Try with Eloquent
17Product::create($products);
18// General error: 1364 Field 'name' doesn't have a default value...
19 
20// Try with Query Builder:
21Product::insert($products);
22// Result: "true" with 2 records inserted

There's no create() or createMany() in Eloquent for multiple records.

That's why insert() is often used in bulk statements like importing data from CSV or another source, instead of doing a much slower foreach with many Model::create() statements.

avatar

Thanks! Good to know. So, the main difference is - when you need to insert a lot of records at once - use inser(). Happy, healthy 2023!

👍 2

Like our articles?

Become a Premium Member for $129/year or $29/month

Recent Premium Tutorials