PHPackages                             visualbuilder/versionable - 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. visualbuilder/versionable

ActiveLibrary

visualbuilder/versionable
=========================

Make Laravel model versionable with polymorphic user support (Fork of overtrue/laravel-versionable).

1.0.3(6mo ago)01.1k—0%1MITPHPPHP ^8.1CI passing

Since Oct 23Pushed 6mo agoCompare

[ Source](https://github.com/visualbuilder/versionable)[ Packagist](https://packagist.org/packages/visualbuilder/versionable)[ RSS](/packages/visualbuilder-versionable/feed)WikiDiscussions 1.x Synced 1mo ago

READMEChangelogDependencies (8)Versions (6)Used By (1)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a06f5c971c160195b885abdacf2659153d460604fe7ae21e1d1a9f3b9e10c2c3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f76697375616c6275696c6465722f76657273696f6e61626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/visualbuilder/filament-versionable)[![run-tests](https://github.com/visualbuilder/versionable/actions/workflows/run-tests.yml/badge.svg?branch=1.x)](https://github.com/visualbuilder/versionable/actions/workflows/run-tests.yml)

Laravel Versionable (Polymorphic User Fork)
===========================================

[](#laravel-versionable-polymorphic-user-fork)

**Fork of [overtrue/laravel-versionable](https://github.com/overtrue/laravel-versionable) with polymorphic user support**

This fork extends the original package to support polymorphic user relationships, allowing you to track versions created by different user model types (e.g., Admin, Associate, EndUser, etc.) in applications with multiple authentication guards.

It's a minimalist way to make your model support version history, and it's very simple to revert to the specified version.

What's Different in This Fork?
------------------------------

[](#whats-different-in-this-fork)

This fork replaces the single-user foreign key relationship with a **polymorphic relationship**, enabling:

- Support for multiple user model types (Admin, Associate, OrganisationUser, etc.)
- Automatic tracking of which user type created each version
- Compatibility with applications using multiple authentication guards
- No configuration needed - uses `auth()->user()` to automatically detect the authenticated user

### Key Changes:

[](#key-changes)

1. **Migration**: Uses `morphs('user')` instead of `unsignedBigInteger('user_id')`
2. **Version Model**: Uses `morphTo()` for the user relationship instead of `belongsTo()`
3. **Configuration**: Removed `user_model` and `user_foreign_key` config options (no longer needed)
4. **Versionable Trait**: New `getVersionUser()` method returns the authenticated user model

Requirement
-----------

[](#requirement)

1. PHP &gt;= 8.1.0
2. laravel/framework &gt;= 9.0

Features
--------

[](#features)

- Keep the specified number of versions.
- Whitelist and blacklist for versionable attributes.
- Easily revert to the specified version.
- Record only changed attributes.
- Easy to customize.

Installing
----------

[](#installing)

Run:-

```
composer require visualbuilder/versionable
```

First, publish the config file and migrations:

```
php artisan vendor:publish --provider="Visualbuilder\Versionable\ServiceProvider"
```

Then run this command to create a database migration:

```
php artisan migrate
```

Usage
-----

[](#usage)

Add `Visualbuilder\Versionable\Versionable` trait to the model and set versionable attributes:

```
use Visualbuilder\Versionable\Versionable;

class Post extends Model
{
    use Versionable;

    /**
     * Versionable attributes
     *
     * @var array
     */
    protected $versionable = ['title', 'content'];

    // Or use a blacklist
    //protected $dontVersionable = ['created_at', 'updated_at'];

}
```

Versions will be created on the versionable model saved.

```
$post = Post::create(['title' => 'version1', 'content' => 'version1 content']);
$post->update(['title' => 'version2']);
```

### Polymorphic user example

[](#polymorphic-user-example)

```
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Visualbuilder\Versionable\Version;

class Admin extends Authenticatable
{
    use SoftDeletes;

    public function versions()
    {
        return $this->morphMany(Version::class, 'user');
    }
}
```

Once you attach the trait to a versionable model, versions automatically store the currently authenticated user.

```
$admin = Admin::find(1);
auth()->login($admin);

$post = Post::create(['title' => 'Draft', 'content' => '...']);
$version = $post->latestVersion;

$version->user; // instance of Admin
$admin->versions()->latest()->get(); // morphMany inverse relationship
```

You can repeat the same pattern for any additional authenticatable model that should appear as a version author.

### Get versions

[](#get-versions)

```
$post->versions; // all versions
$post->latestVersion; // latest version
// or
$post->lastVersion;

$post->versions->first(); // first version
// or
$post->firstVersion;

$post->versionAt('2022-10-06 12:00:00'); // get version from a specific time
// or
$post->versionAt(\Carbon\Carbon::create(2022, 10, 6, 12));
```

### Revert

[](#revert)

Revert a model instance to the specified version:

```
$post->getVersion(3)->revert();

// or

$post->revertToVersion(3);
```

#### Revert without saving

[](#revert-without-saving)

```
$version = $post->versions()->first();

$post = $version->revertWithoutSaving();
```

### Remove versions

[](#remove-versions)

```
// soft delete
$post->removeVersion($versionId = 1);
$post->removeVersions($versionIds = [1, 2, 3]);
$post->removeAllVersions();

// force delete
$post->forceRemoveVersion($versionId = 1);
$post->forceRemoveVersions($versionIds = [1, 2, 3]);
$post->forceRemoveAllVersions();
```

### Restore deleted version by id

[](#restore-deleted-version-by-id)

```
$post->restoreTrashedVersion($id);
```

### Temporarily disable versioning

[](#temporarily-disable-versioning)

```
// create
Post::withoutVersion(function () use (&$post) {
    Post::create(['title' => 'version1', 'content' => 'version1 content']);
});

// update
Post::withoutVersion(function () use ($post) {
    $post->update(['title' => 'updated']);
});
```

### Custom Version Store strategy

[](#custom-version-store-strategy)

You can set the following different version policies through property `protected $versionStrategy`:

- `Visualbuilder\Versionable\VersionStrategy::DIFF` - Version content will only contain changed attributes (default strategy).
- `Visualbuilder\Versionable\VersionStrategy::SNAPSHOT` - Version content will contain all versionable attribute values.

### Show diff between the two versions

[](#show-diff-between-the-two-versions)

```
$diff = $post->getVersion(1)->diff($post->getVersion(2));
```

`$diff` is a object `Visualbuilder\Versionable\Diff`, it based on [jfcherng/php-diff](https://github.com/jfcherng/php-diff).

You can render the diff to [many formats](https://github.com/jfcherng/php-diff#introduction), and all formats result will be like follows:

```
[
    $attribute1 => $diffOfAttribute1,
    $attribute2 => $diffOfAttribute2,
    ...
    $attributeN => $diffOfAttributeN,
]
```

#### toArray()

[](#toarray)

```
$diff->toArray();
//
[
    "name" => [
        "old" => "John",
        "new" => "Doe",
    ],
    "age" => [
        "old" => 25,
        "new" => 26,
    ],
]
```

### Other formats

[](#other-formats)

```
toArray(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toJsonText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toContextText(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toInlineHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toJsonHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
toSideBySideHtml(array $differOptions = [], array $renderOptions = [], bool $stripTags = false): array
```

> **Note**
>
> `$differOptions` and `$renderOptions` are optional, you can set them following the README of [jfcherng/php-diff](https://github.com/jfcherng/php-diff#example). `$stripTags` allows you to remove HTML tags from the Diff, helpful when you don't want to show tags.

### Using custom version model

[](#using-custom-version-model)

You can define `$versionModel` in a model, that used this trait to change the model(table) for versions

> **Note**
>
> Model MUST extend class `\Visualbuilder\Versionable\Version`;

```
