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 EloquentProduct::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.
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 EloquentProduct::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.
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!