PHP
Efficient Mass Updates for Multiple Eloquent Records
Learn to perform highly efficient mass updates on multiple records in Laravel Eloquent using a single database query, significantly boosting performance for bulk operations.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function deactivateInactiveUsers()
{
// Deactivate all users who haven't logged in for 90 days
$deactivatedCount = User::where('last_login_at', '<', now()->subDays(90))
->where('is_active', true)
->update(['is_active' => false, 'deactivated_at' => now()]);
return response()->json(['message' => "{$deactivatedCount} users deactivated."]);
}
public function updatePostCategories(Request $request)
{
$categoryIds = $request->input('category_ids'); // Array of category IDs
$newStatus = $request->input('status'); // e.g., 'published', 'draft'
if (empty($categoryIds) || !in_array($newStatus, ['published', 'draft'])) {
return response()->json(['message' => 'Invalid input.'], 400);
}
// Update status for all posts belonging to the given categories
$updatedCount = Post::whereIn('category_id', $categoryIds)
->update(['status' => $newStatus, 'updated_at' => now()]);
return response()->json(['message' => "{$updatedCount} posts updated."]);
}
}
How it works: Eloquent's `update()` method, when called on a query builder instance (e.g., after `where()` or `whereIn()`), performs a mass update directly at the database level using a single SQL query. This is significantly more efficient than retrieving each model, modifying it, and then saving it individually, especially when dealing with a large number of records. It bypasses the model lifecycle events (like `creating`, `updating`, etc.) unless specifically configured, offering a performance advantage for bulk operations.