Optimize Bulk Insertions with Laravel's New fillAndInsert() Method

Bulk inserting Eloquent models but need casts and timestamps applied? Laravel's new fillAndInsert() method provides an elegant solution by handling model casting and attribute preparation during mass insertion.
When performing bulk insertions in Laravel, you often face a trade-off: use insert() for efficiency but lose Eloquent's casting and attribute preparation, or create and save individual models for full functionality but sacrifice performance. The new fillAndInsert() method bridges this gap by applying model-level casting, timestamps, and UUID generation while maintaining the efficiency of bulk insertions.
Let's see how it works:
User::fillAndInsert([
[
'name' => 'Taylor',
'email' => 'taylor@example.com',
'role' => UserRole::Admin,
],
[
'name' => 'Nuno',
'email' => 'nuno@example.com',
'role' => 3, // Will be cast to enum
],
]);
Real-World Example
This method is particularly valuable when bulk inserting records that need to leverage Eloquent's casting capabilities, such as enum casts, date casts, or UUID generation:
class Product extends Model
{
protected $fillable = [
'name', 'price', 'status', 'category_id', 'attributes'
];
protected function casts(): array
{
return [
'price' => 'decimal:2',
'status' => ProductStatus::class,
'attributes' => 'array',
'id' => 'string',
];
}
public static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->id)) {
$model->id = Str::uuid();
}
});
}
}
// Bulk insert with proper casting and UUID generation
Product::fillAndInsert([
[
'name' => 'Laptop Pro',
'price' => '1299.99',
'status' => ProductStatus::Available,
'attributes' => ['color' => 'silver', 'ram' => '16GB'],
],
[
'name' => 'Wireless Earbuds',
'price' => '199.50',
'status' => 'available', // String will be cast to enum
'attributes' => json_encode(['color' => 'black', 'battery' => '24h']), // String will be cast to array
],
[
'name' => 'Smart Watch',
'price' => 299,
'status' => 1, // Integer will be cast to enum
'attributes' => ['color' => 'blue', 'size' => 'medium'],
],
]);
By leveraging the new fillAndInsert() method, you can write cleaner, more consistent bulk insertion code while still benefiting from Eloquent's powerful casting and attribute preparation capabilities.
If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter (https://x.com/harrisrafto), Bluesky (https://bsky.app/profile/harrisrafto.eu), and YouTube (https://www.youtube.com/@harrisrafto). It helps a lot!