PHPackages                             sofa/laravel-history - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. sofa/laravel-history

ActiveLibrary

sofa/laravel-history
====================

0.1.1(4y ago)72731MITPHPPHP &gt;=8.0

Since Jun 13Pushed 4y ago1 watchersCompare

[ Source](https://github.com/jarektkaczyk/laravel-history)[ Packagist](https://packagist.org/packages/sofa/laravel-history)[ Docs](https://github.com/sofa/history)[ GitHub Sponsors](https://github.com/sponsors/jarektkaczyk)[ RSS](/packages/sofa-laravel-history/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (8)Versions (3)Used By (0)

Eloquent History
================

[](#eloquent-history)

[![Latest Version on Packagist](https://camo.githubusercontent.com/70f366145deb78e930087f5336c395b90cb6bc155eb194ee55c8d403f76c3b81/68747470733a2f2f706f7365722e707567782e6f72672f736f66612f6c61726176656c2d686973746f72792f762f737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/sofa/laravel-history)[![GitHub Tests Action Status](https://github.com/jarektkaczyk/laravel-history/workflows/Tests/badge.svg)](https://github.com/jarektkaczyk/laravel-history/actions/workflows/run-tests.yml?branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/8f6ea7c7c0e06a23d80dfc5fb0686278edb943467912c78519a52c5fac0ea91d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736f66612f6c61726176656c2d686973746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/sofa/laravel-history)

No-setup history recording for your Eloquent models. Just install, migrate, and it works!

Roadmap (contributions most welcome 🙏🏼)
---------------------------------------

[](#roadmap-contributions-most-welcome-)

- retention [configuration &amp; command](./config/history.php)
- bundle frontend implementation to present history in a beautiful form **blade**
- bundle frontend implementation to present history in a beautiful form **vue**
- bundle frontend implementation to present history in a beautiful form **TALL stack**
- bundle frontend implementation to present history in a beautiful form **react**

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require sofa/laravel-history
```

Then publish migrations and config, then run migrations to create the necessary table:

```
php artisan vendor:publish --provider="Sofa\History\HistoryServiceProvider"
php artisan migrate
```

This is the contents of the published config file:

```
return [
    /**
     * Model of the User performing actions and recorded in the history.
     *
     * @see \Sofa\History\History::user()
     */
    'user_model' => 'App\Models\User',

    /**
     * Custom user resolver for the actions recorded by the package.
     * Should be callable returning a User performing an action, or their raw identifier.
     * By default auth()->id() is used.
     *
     * @see \Sofa\History\HistoryListener::getUserId()
     */
    'user_resolver' => null,

    /**
     * **RETENTION** requires adding cleanup command to your schedule
     *
     * Retention period for the history records.
     * Accepts any parsable date string, eg.
     * '2021-01-01' -> retain anything since 2021-01-01
     * '3 months' -> retain anything no older than 3 months
     * '1 year' -> retain anything no older than 1 year
     * @see strtotime()
     *
     * @see \Sofa\History\RetentionCommand
     */
    'retention' => null,
];
```

Usage
-----

[](#usage)

#### Time travel with your models:

[](#time-travel-with-your-models)

```
$postFromThePast = History::recreate(Post::class, $id, '2020-12-10', ['categories']);
// or: $postFromThePast = Post::recreate($id, '2020-12-10', ['categories']);

// model attributes as of 2020-12-10:
$postFromThePast->title;

// relations as of 2020-12-10:
$postFromThePast->categories->count()

// related models attributes also as of 2020-12-10:
$postFromThePast->categories->first->name;
```

#### Get a full history/audit log of your models

[](#get-a-full-historyaudit-log-of-your-models)

```
$history = History::for($post)->get();

# For each update in the history you will get an entry like below:
>>> $history->first()
=> Sofa\History\History {#4320
     id: 16,
     model_type: "App\Models\Post",
     model_id: 5,
     action: "created",
     data: "{"title": "officiis", "user_id": 5, "created_at": "2021-06-07 00:00:00", "updated_at": "2021-06-07 00:00:00"}",
     user_id: null,
     created_at: "2021-06-07 00:00:00",
     updated_at: "2021-06-07 00:00:00",
   }

# And here you can see a sample of the recorded activity:
>>> $history->pluck('action')
=> Illuminate\Support\Collection {#4315
     all: [
       "created",
       "pivot_attached",
       "pivot_attached",
       "pivot_attached",
       "updated",
       "updated",
       "pivot_detached",
       "pivot_detached",
       "pivot_detached",
       "deleted",
       "restored",
       "pivot_attached",
       "pivot_attached",
     ],
   }
```

#### You can easily create an Audit Log for your users too:

[](#you-can-easily-create-an-audit-log-for-your-users-too)

```
// User model
public function auditLog()
{
    return $this->hasMany(History::class, 'user_id');
}

// Then
$auditLog = auth()->user()->auditLog()->paginate();
```

Additional setup &amp; known limitations
----------------------------------------

[](#additional-setup--known-limitations)

The package offers 2 main functionalities:

- recording full history for a model
- recreating models with all relations in the past

History recording works out of the box for **all your Eloquent models** (really 😉). Additionally it will record and recreate model relations. There are however some limitations due to relations inner workings in Laravel:

- recreating `HasMany`, `BelongsTo`, `MorphTo`, `MorphMany` &amp; `HasManyThrough` is **fully supported out of the box**
- recording and recreating many-to-many relations requires custom pivot model in order for Laravel to fire relevant events (`BelongsToMany`, `MoprhToMany`). If you defined a custom pivot on your relation(s) already, you don't need to do anything. Otherwise, you can use provided placeholder pivot models:

    ```
    // original relations:
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    // change to:
    public function categories()
    {
        return $this->belongsToMany(Category::class)->using(\Sofa\History\PivotEvents::class);
    }

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable')->using(\Sofa\History\MorphPivotEvents::class);
    }
    ```
- `HasOne` relation can be recreated only when specific requirements are met: there is a single `orderBy(...)` on the relation definition and there are no *complex* `where(...)` clauses (it **does not affect** recording history, just recreating model with relations):

    ```
    // this will work:
    public function lastComment()
    {
        return $this->hasOne(Comment::class)->latest('id')->whereIn('status', ['approved', 'pending']);
    }

    // this will not work (currently...):
    public function lastComment()
    {
        return $this->hasOne(Comment::class) // no ordering
            ->where(fn ($q) => $q->where(...)->orWhere(...)); // unsupported where clause
    }
    ```

    - `HasOneThrough` is currently not supported at all

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Jarek Tkaczyk](https://github.com/jarektkaczyk)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

2

Last Release

1788d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/34d383bf50d6c73fc747d89a5efacd41ccecc9695aec04148a7c04fc00ef26e7?d=identicon)[jarektkaczyk](/maintainers/jarektkaczyk)

---

Top Contributors

[![jarektkaczyk](https://avatars.githubusercontent.com/u/6928818?v=4)](https://github.com/jarektkaczyk "jarektkaczyk (9 commits)")

---

Tags

historysofa

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sofa-laravel-history/health.svg)

```
[![Health](https://phpackages.com/badges/sofa-laravel-history/health.svg)](https://phpackages.com/packages/sofa-laravel-history)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[owen-it/laravel-auditing

Audit changes of your Eloquent models in Laravel

3.4k33.0M95](/packages/owen-it-laravel-auditing)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.1M11](/packages/bavix-laravel-wallet)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
