Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,20 @@ $user->update([
]);
```

<a name="createInitialVersion" />

### Create initial version for an existing model

When you integrate versionable package in an existing project, you might want to create initial versions for the existing models
without making any actual changes.

This can be achieved by using the `saveVersion` method on the versionable model.

```php
$user = User::find(1);
$user->saveVersion();
```

<a name="differentVersionTable" />

### Use different version table
Expand Down
41 changes: 25 additions & 16 deletions src/Mpociot/Versionable/VersionableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ protected function versionablePreSave()
}

/**
* Save a new version.
* Save a new version if it is valid for saving.
* @return void
*/
protected function versionablePostSave()
Expand All @@ -168,25 +168,34 @@ protected function versionablePostSave()
( $this->versioningEnabled === true && !$this->updating && !is_null($this->versionableDirtyData) && count($this->versionableDirtyData))
) {
// Save a new version
$class = $this->getVersionClass();
$version = new $class();
$version->versionable_id = $this->getKey();
$version->versionable_type = method_exists($this, 'getMorphClass') ? $this->getMorphClass() : get_class($this);
$version->user_id = $this->getAuthUserId();

$versionedHiddenFields = $this->versionedHiddenFields ?? [];
$this->makeVisible($versionedHiddenFields);
$version->model_data = serialize($this->attributesToArray());
$this->makeHidden($versionedHiddenFields);
$this->saveVersion();

if (!empty( $this->reason )) {
$version->reason = $this->reason;
}
$this->purgeOldVersions();
}
}

/**
* Save a new version.
* @return void
*/
public function saveVersion()
{
$class = $this->getVersionClass();
$version = new $class();
$version->versionable_id = $this->getKey();
$version->versionable_type = method_exists($this, 'getMorphClass') ? $this->getMorphClass() : get_class($this);
$version->user_id = $this->getAuthUserId();

$version->save();
$versionedHiddenFields = $this->versionedHiddenFields ?? [];
$this->makeVisible($versionedHiddenFields);
$version->model_data = serialize($this->attributesToArray());
$this->makeHidden($versionedHiddenFields);

$this->purgeOldVersions();
if (!empty( $this->reason )) {
$version->reason = $this->reason;
}

$version->save();
}

/**
Expand Down