I am observing a Laravel pivot model PermissionUser. Whenever anything changes in the Pivot, my observer catch the event and store the changes of model in history collection in MongoDB.
The problem is, sometime bulk permission assign can happen, on that case, my observe trigger for every event call to mongoDB to store the changes for each assignment.
How to observe the model efficiently so that I need to call the DB once for a bulk permission assignment...
catch the event.
public function created(PermissionUser $permissionUser)
{
$changes = $permissionUser->getAttributes();
event(new ModelChanged($permissionUser, 'Permission, Added', $changes));
}
Listener for the event.
public function onModelChanged(ModelChanged $event): void
{
if(!HistoryObserver::filter(null)) {
return;
}
$event->model->morphMany(History::class, 'model')->create([
'message' => $event->message,
'meta' => $event->meta,
'user_id' => HistoryObserver::getUserID(),
'user_type' => HistoryObserver::getUserType(),
'performed_at' => Carbon::now()->toDateTimeString(),
]);
}
Thank you for the time.