0

My question is about spatie/ActivityLog. There had a better way than below to log mass updates with spatie/ActivityLog? Maybe without use foreach? My solution:

$newStatus = 1;
$resultList = Model::where('Status', 0)->get();
LogBatch::startBatch();
foreach($resultList AS $result){
$result->Status = $NewStatus;
$result->save();
}
LogBatch::endBatch();

I looking something similar like this when one line update happens:

Model::where('Id', 1)->first()->update(['Status'] => $newStatus);

Laravel: 9+, PHP: 8+, spatie/laravel-activitylog: 4.6

I tried to found the solution many google,stackoverflow search and its is working just fine now. May there is no better solution but may there is, and i want to make a simplier, cleaner, readable and may faster code.

Thank you all!

EvilDeadTX
  • 29
  • 1
  • 7

1 Answers1

1

Unless the selection logic is more complicated than what you posted in your question, you can simply update directly

$newStatus = 1;
$resultList = Model::where('Status', 0)->update(['Status' => $newStatus]);

Or if you need the ids

$newStatus = 1;
$resultIds = Model::where('Status', 0)->pluck('id')->toArray();

LogBatch::startBatch();
Model::whereIn('id', $resultIds)->update(['Status' => $newStatus]);
LogBatch::endBatch();
N69S
  • 16,110
  • 3
  • 22
  • 36
  • I tried, and the update is going well with this solution. But do not create any update log for them in DB. But with my solution create them. Any idea why? Thank you! – EvilDeadTX Nov 17 '22 at 10:29
  • 1
    @EvilDeadTX Since the model is not even instantiated, no callback on update is fired. it's the most effective way but it works around the logic in your code. Before you ask, you cant do both (without a lot of code change), either use the loop to fire each update event or work around it to make it fast. link to an issue related to this https://github.com/spatie/laravel-activitylog/issues/240 – N69S Nov 17 '22 at 10:33