phplaraveleloquentlaravel-9activitylog

Mass Update spatie/ActivityLog Laravel Better Solution?


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!


Solution

  • 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();