PHP

Efficient Bulk Insertion and Updating of Eloquent Records

Perform bulk insert and update operations in Laravel Eloquent efficiently using `insert()` for new records and `update()` for existing ones.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'quantity'];
}

// --- Usage Examples ---

// Bulk Insert multiple records
$newProductsData = [
    ['name' => 'Laptop', 'price' => 1200.00, 'quantity' => 50, 'created_at' => now(), 'updated_at' => now()],
    ['name' => 'Mouse', 'price' => 25.00, 'quantity' => 200, 'created_at' => now(), 'updated_at' => now()],
    ['name' => 'Keyboard', 'price' => 75.00, 'quantity' => 150, 'created_at' => now(), 'updated_at' => now()],
];
Product::insert($newProductsData); // Returns true on success

// Bulk Update multiple records based on a condition
// Increase price by 10% for all products with quantity less than 100
Product::where('quantity', '<', 100)->update([
    'price' => \DB::raw('price * 1.10'), // Using DB::raw for expressions
    'updated_at' => now(),
]);

// Bulk Update all products
// Set 'in_stock' status to false for all products (assuming 'in_stock' column exists)
// Product::query()->update(['in_stock' => false, 'updated_at' => now()]);

// Update specific products by their IDs
Product::whereIn('id', [1, 2, 3])->update(['quantity' => 0, 'updated_at' => now()]);
How it works: This snippet focuses on performing efficient bulk operations using Eloquent. The `insert()` method allows you to insert multiple new records into a table with a single query, significantly improving performance compared to creating and saving individual model instances in a loop. Similarly, the `update()` method, when called on a query builder instance (e.g., with `where()` or `whereIn()`), can update multiple records that match the query's criteria with a single database command, avoiding the overhead of fetching and updating each model separately. Note that `insert()` does not hydrate models, nor does it fire model events.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs