The GDPR tells you to keep personal data only as long as you need it. In a real application, this is difficult. A user deletes the account, but the row stays in the database for a period. An old order keeps a name, an email address and a phone number. Each project needs a rule for this data, and each project writes the rule again.

We made this rule into a package: Laravel Data Scrubber. It finds the records that you no longer need, and it replaces or removes the personal data in them.

What the package does

  • You tell the package which records to clean, with a normal Eloquent query.
  • You tell the package how to clean each field. Each field gets a strategy.
  • A command finds the records and cleans them on the queue, in chunks.
  • The package records when it cleaned a record, so it does not clean the same record two times.
  • It sends an event after each record. It can also clean the personal data in your activity log.

Install the package

composer require bernskiold/laravel-data-scrubber

The package uses a queue with the name data-scrubber. If you use Laravel Horizon, add this queue to a supervisor in config/horizon.php.

Make a model scrubbable

Implement the Scrubbable interface and use the ScrubsData trait. Then add two methods.

The first method, scrubbableQuery(), tells the package which records to clean. In this example, the package cleans users that were soft-deleted more than 30 days ago.

The second method, scrubbableFields(), tells the package how to clean each field.

use Bernskiold\LaravelDataScrubber\Concerns\ScrubsData;
use Bernskiold\LaravelDataScrubber\Contracts\Scrubbable;
use Bernskiold\LaravelDataScrubber\Data\ScrubbableFields;
use Bernskiold\LaravelDataScrubber\Strategies\AnonymizeEmailWithIdStrategy;
use Bernskiold\LaravelDataScrubber\Strategies\AnonymizeFirstNameStrategy;
use Bernskiold\LaravelDataScrubber\Strategies\AnonymizeLastNameStrategy;
use Bernskiold\LaravelDataScrubber\Strategies\DeleteFileStrategy;
use Bernskiold\LaravelDataScrubber\Strategies\NullStrategy;

class User extends Model implements Scrubbable
{
    use ScrubsData;
    use SoftDeletes;

    public function scrubbableQuery(): Builder
    {
        return static::query()
            ->onlyTrashed()
            ->where('deleted_at', '<', now()->subDays(30))
            ->whereNull('scrubbed_at');
    }

    public function scrubbableFields(): ScrubbableFields
    {
        return ScrubbableFields::make([
            'email' => AnonymizeEmailWithIdStrategy::class,
            'first_name' => AnonymizeFirstNameStrategy::class,
            'last_name' => AnonymizeLastNameStrategy::class,
            'phone' => NullStrategy::class,
            'profile_photo' => DeleteFileStrategy::class,
        ]);
    }
}

Add the timestamp column to the table with the scrubbedAt() macro:

$table->scrubbedAt();

Select a strategy for each field

The package has a strategy for most types of data. Some examples:

  • NullStrategy sets the value to null.
  • RedactedStrategy replaces the value with [REDACTED].
  • AnonymizeEmailWithIdStrategy replaces the email address with an address such as [email protected]. The address stays unique.
  • HashStrategy replaces the value with a hash.
  • MaskStrategy hides the middle of the value, for example 12******90.
  • TruncateStrategy keeps the first characters, for example Jon***.
  • IpAnonymizeStrategy sets the last parts of an IP address to zero.
  • DeleteFileStrategy deletes the file from the disk and sets the value to null.

You can also give settings to a strategy. JsonFieldStrategy cleans only some keys in a JSON column. ConditionalStrategy selects a strategy from a condition. CallbackStrategy uses your own function.

'phone' => new MaskStrategy(visibleStart: 2, visibleEnd: 2, maskChar: '*'),

'metadata' => new JsonFieldStrategy([
    'phone' => new MaskStrategy(2, 2),
    'address' => RedactedStrategy::class,
]),

A hash of an email address or a phone number is not always safe. A person can calculate the hashes of many known values and compare them. To prevent this, set a secret salt in data-scrubber.strategies.hash.salt. Then HashStrategy uses an HMAC. Set the salt before you clean the first record, because a different salt gives a different result.

Run the scrubber

Use the data-scrubbing:scrub command. First, use --dry-run to see which records the command will clean.

php artisan data-scrubbing:scrub --dry-run
php artisan data-scrubbing:scrub --force

Add the command to your schedule to clean the data each day. You can also use --model=User to clean only one model, and --sync to clean the records without the queue.

The data-scrubbing:config command shows each scrubbable model, its fields and its strategies. This is a good check before you start.

You can also clean one record in your code:

$user->previewScrub(); // Shows the changes
$user->scrub();

Safe on large tables

Each queued job cleans one chunk of records. If more records remain, the job sends a new job for the next chunk. When a job fails, it does the work again for its own chunk only.

The package cleans only the records that it has not cleaned before. Thus, a retry does not apply a strategy such as HashStrategy two times.

Clean the activity log too

Personal data is often also in an activity log. If you use Spatie Activity Log, the package has two listeners for the Scrubbed event:

  • LogScrubbedActivity records that the package cleaned a record. It records the field names and the strategies. It never records the data.
  • ScrubActivityLogListener cleans the old values in the activity log entries of the record. It uses the same strategies as the model.

A limit to know

Laravel merges a published config file with the package config at the top level only. If you publish config/data-scrubber.php, keep the full strategies and queue arrays. If you remove a key from one of these arrays, Laravel does not merge it back from the package config.

Get the package

Laravel Data Scrubber is open source, with the MIT license. The code and the full documentation are on GitHub. If you find a problem or have an idea, open an issue. We are happy to hear from you.