Duplicate records occur in every application that lives long enough. Two people add the same company. An import creates a second contact with the same email address. Then a person asks you to merge them.
A merge is more work than it seems. You must move all the related records, such as orders, notes and tags. You must decide which values to keep. And you must do all of this safely, so that no data is lost. We wrote this code for several clients. Now it is a package: Laravel Record Merge.
What the package does
Laravel Record Merge merges a source record into a target record of the same model. After the merge, only the target record remains.
- It finds the relations of the model by itself.
- It moves the related records from the source to the target.
- It copies values from the source when the target has no value.
- It lets you choose, for each attribute, which value to keep.
- It gives a preview of the merge before you start it.
- It runs the merge in a database transaction, on the queue.
- It sends an event when the merge is complete, and an event when it fails.
Install the package
composer require bernskiold/laravel-record-merge
You can publish the configuration file to change the queue, the relation handlers and the loggers:
php artisan vendor:publish --provider="Bernskiold\LaravelRecordMerge\LaravelRecordMergeServiceProvider" --tag="config"
Prepare the model
Implement the Mergeable contract and add the SupportsMerging trait:
use Bernskiold\LaravelRecordMerge\Concerns\SupportsMerging;
use Bernskiold\LaravelRecordMerge\Contracts\Mergeable;
class Company extends Model implements Mergeable
{
use SupportsMerging;
public function contacts(): HasMany
{
return $this->hasMany(Contact::class);
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
}
The package finds each public method that returns a relation. For this reason, each relation must have a return type.
Preview the merge
Before a person confirms the merge, show them what will occur. The preview does not change data.
$preview = $duplicate->previewMergeTo($company);
$preview->comparison; // The source and target value of each attribute
$preview->relationshipCounts; // The number of related records on each side
Each item in comparison has a sourceValue and a targetValue. Each item in relationshipCounts has a sourceCount and a targetCount. Use these values to build a confirmation screen.
Start the merge
Call mergeTo() on the record that you want to remove. Give the record that you want to keep:
$duplicate->mergeTo($company);
This dispatches a job. The job records the user who started the merge. In a database transaction, the job then does these steps:
- It copies each value from the source when the target value is empty.
- It moves the related records to the target.
- It writes the merge to the log.
- It deletes the source record.
If a step fails, the transaction rolls back. When the merge is complete, the job sends a RecordMerged event. When the job fails, it sends a RecordMergeFailed event. Use these events to tell the person the result.
Choose the values to keep
By default, the target keeps its own values. The source only fills in the empty values. To change this for an attribute, give a MergeConfig:
use Bernskiold\LaravelRecordMerge\Data\MergeConfig;
use Bernskiold\LaravelRecordMerge\Enums\MergeStrategy;
$duplicate->mergeTo($company, MergeConfig::make([
'phone' => MergeStrategy::UseSource,
'website' => MergeStrategy::UseTarget,
'notes' => MergeStrategy::Skip,
]));
The package never merges the primary key, the timestamps or the soft delete column. To protect more attributes, return them from getNotMergeableAttributes().
How the relations move
The package has a handler for each type of relation:
- For
HasOne,HasManyandMorphMany, it changes the foreign key to the target. - For
BelongsToManyandMorphToMany, it moves the pivot rows and keeps the pivot data. If the target already has the relation, it does not add it again. - For
BelongsToandMorphTo, it does nothing. The attribute merge handles these, because the foreign key is on the model.
Some relations must not move. An activity log is a good example. Return these relation names from getProtectedRelationships(). If you use spatie/laravel-activitylog, the package protects the activities relation by default.
You can add your own handler for other relation types in the configuration file.
Log the merge
After a merge, the source record is gone. A log helps you find what occurred. If spatie/laravel-activitylog is installed, the package writes each merge to the activity log. To use a different log, implement the MergeLogger contract and add it to the configuration.
Find possible duplicates
A merge screen needs a search for the target record. The trait gives getPossibleRecordsForMerging(). If the model uses Laravel Scout, the method uses the Scout search. Override this method to add your own search rules.
A limit to know
The package finds relations through the return type of each method. A relation method without a return type is not found, and its records do not move. Before the source is deleted, these records can be lost, or the delete can fail because of a foreign key. Add a return type to each relation before you use the package.
Get the package
Laravel Record Merge is open source, with the MIT license. The code is on GitHub. If you find a problem or have an idea, open an issue. We are happy to hear from you.