PHP

Perform Batch Updates and Deletes Efficiently

Execute mass updates or deletes on multiple records without retrieving and iterating over each individual Eloquent model, optimizing database operations.

// Example: Update the 'status' for all inactive users
use App\Models\User;

User::where('last_activity_at', '<', now()->subMonths(6))
    ->update(['status' => 'inactive', 'updated_at' => now()]); // updated_at is not auto-managed

// Example: Increment the 'views_count' for all published posts
use App\Models\Post;

Post::where('is_published', true)
    ->increment('views_count'); // Handles a single numeric column

// Example: Delete all posts older than 1 year
Post::where('created_at', '<', now()->subYears(1))
    ->delete(); // This still respects soft deletes if configured

// To force delete (bypass soft deletes):
// Post::where('created_at', '<', now()->subYears(1))->forceDelete();
How it works: Eloquent's `update()`, `delete()`, `increment()`, and `decrement()` methods can be called directly on a query builder instance to perform mass modifications. Unlike retrieving models first and then calling `save()` on each, these methods execute a single SQL query, bypassing the hydration of individual Eloquent models. This significantly improves performance for batch operations, especially with a large number of records. Note that model events are generally *not* fired when using these mass methods directly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs