22
33namespace MrAdder \FilamentLogger \Loggers ;
44
5+ use BadMethodCallException ;
56use Filament \Facades \Filament ;
67use Illuminate \Auth \GenericUser ;
78use Illuminate \Contracts \Auth \Authenticatable ;
89use Illuminate \Database \Eloquent \Model ;
910use Illuminate \Support \Str ;
1011use MrAdder \FilamentLogger \Support \LogDataSanitizer ;
12+ use MrAdder \FilamentLogger \Support \PreviousAttributesStore ;
1113use MrAdder \FilamentLogger \Support \ReplicationContextStore ;
1214use Spatie \Activitylog \ActivityLogger ;
1315use Spatie \Activitylog \ActivityLogStatus ;
@@ -141,9 +143,23 @@ protected function buildProperties(Model $model, array $attributes = [], array $
141143 /**
142144 * @return array<string, mixed>
143145 */
144- protected function getPreviousAttributes (Model $ model ): array
146+ protected function getPreviousAttributes (Model $ model, bool $ forget = false ): array
145147 {
146- return $ model ->getPrevious ();
148+ $ storedAttributes = $ forget
149+ ? PreviousAttributesStore::pull ($ model )
150+ : PreviousAttributesStore::get ($ model );
151+
152+ if ($ storedAttributes !== []) {
153+ return $ storedAttributes ;
154+ }
155+
156+ try {
157+ return $ model ->getPrevious ();
158+ } catch (BadMethodCallException ) {
159+ $ changes = $ model ->getChanges ();
160+
161+ return array_intersect_key ($ model ->getOriginal (), $ changes );
162+ }
147163 }
148164
149165 protected function isForceDeleting (Model $ model ): bool
@@ -186,6 +202,20 @@ public function created(Model $model)
186202 $ this ->log ($ model , 'Created ' , properties: $ this ->buildProperties ($ model , $ model ->getAttributes ()));
187203 }
188204
205+ public function updating (Model $ model ): void
206+ {
207+ $ dirty = $ model ->getDirty ();
208+
209+ if ($ dirty === []) {
210+ return ;
211+ }
212+
213+ PreviousAttributesStore::remember (
214+ $ model ,
215+ array_intersect_key ($ model ->getOriginal (), $ dirty ),
216+ );
217+ }
218+
189219 public function updated (Model $ model )
190220 {
191221 $ changes = $ this ->getLoggableAttributes ($ model , $ model ->getChanges ());
@@ -196,6 +226,7 @@ public function updated(Model $model)
196226 }
197227
198228 $ this ->log ($ model , 'Updated ' , properties: $ this ->buildProperties ($ model , $ changes , $ previous ));
229+ PreviousAttributesStore::forget ($ model );
199230 }
200231
201232 public function deleted (Model $ model )
@@ -210,7 +241,7 @@ public function deleted(Model $model)
210241 public function restored (Model $ model )
211242 {
212243 $ changes = $ model ->getChanges ();
213- $ previous = $ this ->getPreviousAttributes ($ model );
244+ $ previous = $ this ->getPreviousAttributes ($ model, true );
214245
215246 $ this ->log (
216247 $ model ,
0 commit comments