Introduce `withRecordableEvents` function
Because:
- It can be handy to, based on context, record certain events that you don't usually want recorded. This allows you, for example, to not record "retrieved" events all them time, but just when you specifically want to. Using a closure based approach means that the events are restored for future events in the system to be recorded.
This commit:
- Adds the
withRecordableEventsmethod to theRecordabletrait - Adds tests around the feature
Example...
public function show(User $user)
{
$user->withRecordableEvents('retrieved', function ($user) {
Accountant::record($user, 'retrieved'));
});
return UserResource::make($user);
}
public function index()
{
// don't want it recorded here...
$users = User::all();
return UserResource::collection($users);
}
Having it restore the recordable events once the closure has been called means that any future calls that trigger events will be recorded as expected.
This is a pattern Laravel uses internally with functions like Model::withoutEvents($closure)
Edited by Tim MacDonald