Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Eloquent create() VS Query Builder insert() Method

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

$product = [
'name' => 'Some product',
'price' => 123,
'stock_left' => 999
];
 
// You can use Eloquent
Product::create($product); // don't forget to fill $fillable in Model
 
// Or you can use Query Builder:
Product::insert($product);

There are a few differences.


Difference 1. Return Model vs Boolean

Here are the results of the queries above:

// Returned after Product::create():
 
App\Models\Product {#3866
name: "Some product",
price: 123,
stock_left: 999,
updated_at: "2023-01-07 08:38:02",
created_at: "2023-01-07 08:38:02",
id: 6,
}
 
// Returned after Product::insert():
 
true

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:

$products = [
[
'name' => 'Some product',
'price' => 123,
'stock_left' => 999
],
[
'name' => 'Other product',
'price' => 456,
'stock_left' => 9999
],
 
// ... more products
];
 
// Try with Eloquent
Product::create($products);
// General error: 1364 Field 'name' doesn't have a default value...
 
// Try with Query Builder:
Product::insert($products);
// 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!

👍 3

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses