PHP code example of philiprehberger / laravel-model-diff
1. Go to this page and download the library: Download philiprehberger/laravel-model-diff library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
philiprehberger / laravel-model-diff example snippets
// config/model-diff.php
return [
/*
| Attributes excluded from every diff comparison.
*/
'ignored_attributes' => [
'created_at',
'updated_at',
'id',
],
/*
| Format string used when rendering date/datetime values in
| DiffResult::toHumanReadable().
*/
'date_format' => 'M j, Y g:i A',
];
use PhilipRehberger\ModelDiff\Facades\ModelDiff;
$before = User::find(42);
// ... some time passes, the record is updated ...
$after = User::find(42);
$result = ModelDiff::compare($before, $after);
if ($result->hasChanges()) {
// ['name', 'email']
$result->changedAttributes();
// Array of AttributeChange objects
$result->getChanges();
// Plain arrays
$result->toArray();
// Keyed by human-readable label
$result->toHumanReadable();
}
$user = User::find(42);
$user->name = 'New Name';
$user->email = '[email protected]';
// Do NOT call save() — inspect the dirty state
$result = ModelDiff::fromDirty($user);
$result->changedAttributes(); // ['name', 'email']
$result = ModelDiff::compare($before, $after);
// Keep only specific attributes
$nameAndEmail = $result->only(['name', 'email']);
// Exclude specific attributes
$withoutMetadata = $result->except(['metadata', 'internal_notes']);
$result = ModelDiff::compare($before, $after);
$result->getBefore('name'); // 'Alice'
$result->getAfter('name'); // 'Bob'
// Returns null when the attribute is not in the diff
$result->getBefore('unchanged_field'); // null
use PhilipRehberger\ModelDiff\Concerns\HasDiffLabels;
class Client extends Model
{
use HasDiffLabels;
protected array $diffLabels = [
'company_name' => 'Company Name',
'is_active' => 'Active Status',
'arr_monthly' => 'Monthly ARR',
];
}
use PhilipRehberger\ModelDiff\ModelDiff;
// Via DI
public function __construct(private ModelDiff $diff) {}
// Directly
$diff = new ModelDiff();
$result = $diff->compare($before, $after);