Logging model events | laravel-activitylog-rust | Spatie       

 SPATIE  

laravel-activitylog-rust
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-activitylog-rust](https://spatie.be/docs/laravel-activitylog-rust/v1)  Advanced-usage  Logging model events

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-activitylog-rust/v1) 

  Logging model events    
- [ Introduction ](https://spatie.be/docs/laravel-activitylog-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-activitylog-rust/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-activitylog-rust/v1/requirements)
- [ Installation and setup ](https://spatie.be/docs/laravel-activitylog-rust/v1/installation-and-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-activitylog-rust/v1/questions-and-issues)
- [ Changelog ](https://spatie.be/docs/laravel-activitylog-rust/v1/changelog)
- [ Upgrading ](https://spatie.be/docs/laravel-activitylog-rust/v1/upgrading)
- [ About us ](https://spatie.be/docs/laravel-activitylog-rust/v1/about-us)
- [ Testing ](https://spatie.be/docs/laravel-activitylog-rust/v1/testing)

Basic usage
-----------

- [ Logging activity ](https://spatie.be/docs/laravel-activitylog-rust/v1/basic-usage/logging-activity)
- [ Cleaning up the log ](https://spatie.be/docs/laravel-activitylog-rust/v1/basic-usage/cleaning-up-the-log)

Advanced usage
--------------

- [ Logging model events ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/logging-model-events)
- [ Log options ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/log-options)
- [ Buffering activities ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/buffering)
- [ Default causer for a logger ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/define-causer-for-runtime)
- [ Using placeholders ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/using-placeholders)
- [ Using multiple logs ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/using-multiple-logs)
- [ Disabling logging ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/disabling-logging)
- [ Custom activity models ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/customizing-actions)
- [ Before logging hook ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/before-logging-hook)
- [ Causer identity ](https://spatie.be/docs/laravel-activitylog-rust/v1/advanced-usage/causer-resolver)

 Logging model events
====================

- Define a native model with `#[model]`.
- Implement `ActivityModel` and select safe columns through `LogOptions`.
- Register `observe::<YourModel>` once with the application's event dispatcher.
- Create, update or delete models through the ORM to record their lifecycle events.

```
use laravel::{Application, model::{model, create, update}};
use spatie_activitylog::{Activity, ActivityModel, service_provider, observe, LogOptions};

#[model]
pub struct Article {
    pub id: i64,
    pub title: String,
    pub text: String,
}

impl ActivityModel for Article {
    fn get_activitylog_options(&self) -> LogOptions {
        LogOptions::defaults()
            .log_only(["title", "text"])
            .log_only_dirty()
            .dont_log_empty_changes()
    }
}

let app = Application::configure()
    .for_testing(directory.path())
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_events(|events, _| { observe::<Article>(events); })
    .create();

let mut article = create!(Article { title: "Draft", text: "Article text" }).await?;
update!(article { title: "Published" }).await?;
article.delete().await?;

let activities = Activity::query().order_by(Activity::id).get().await?;
assert_eq!(activities.len(), 3);
assert_eq!(activities[1].attribute_changes["old"]["title"], "Draft");
assert_eq!(activities[1].attribute_changes["attributes"]["title"], "Published");
```

Register each model once. Ordinary native `create!`, `update!`, `delete` and `destroy`operations dispatch `Created<M>`, `Updated<M>` and `Deleted<M>` events. The package listens inside the write's transaction.

A create records selected new values under `attributes`. Updates use the native `Changes<M>`old values, under `old`, and new values under `attributes`. Deletes record the last values under `old`. A no-op native update emits no event. The tests create, update and delete real SQLite rows, including an update from a durable queue job run by `queue:work`.

`events_to_be_recorded()` can restrict logging to a subset of the three native events. `activity_logging_enabled()` can reject a particular model's events. `before_activity_logged(&self, &mut ActivityDraft, event)` can redact or enrich the activity.

Native bulk query writes and `model::without_events` do not emit model lifecycle events, so they are not observed. Raw SQL is not observed either. An observer failure is returned to the caller. Outside an explicit transaction, a model write may already be committed; wrap model writes in a transaction when the audit must succeed atomically.

There are no native `retrieved`, soft-delete or `restored` events in version 0.1.0. The package does not invent them. Log custom application events explicitly if needed.

Related data is loaded with native typed relations by application code. Provide it through `activity_snapshot` if it belongs in the log. If you format values or derive related fields, also implement `activity_old_snapshot(&Changes<Self>)` to supply their previous values. The default reconstructs old database columns, not arbitrary accessor logic.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
