Redactable Models

Share
Redactable Models
Photo by Paulius Dragunas / Unsplash

Redacting data in models is important, depending on your application. If someone chooses to delete their account, you may wish to retain some of the data for analytics, whilst removing some PII such as name, email address, phone number etc.

Recently, my friend Ash Allen launched a new Composer package which makes this super easy to do. You can check the package out on Github below:

GitHub - ash-jc-allen/redactable-models: A package that allows you to redact, obfuscate, or mask data in your Laravel models.
A package that allows you to redact, obfuscate, or mask data in your Laravel models. - ash-jc-allen/redactable-models

Using the package is a piece of cake. Let's say we have a User model:

class User extends Model
{
    //
}

We need to implement the Redactable interface:

class User extends Model implements Redactable
{
    //
}

This then forces the implementation of two methods; redactable and redactionStrategy. The first one is the query that runs to get which models need redacting. For example you may choose to run this periodically for accounts that registered but never logged in, or users that deleted their account a certain period of time ago. The 2nd one is where you specify the fields you want to redact and what to replace them with:

use AshAllenDesign\RedactableModels\Support\Strategies\ReplaceContents;
use AshAllenDesign\RedactableModels\Interfaces\Redactable;
use Illuminate\Contracts\Database\Eloquent\Builder;

class User extends Model implements Redactable
{
    // ...
    
    public function redactable(): Builder
    {
        return static::query()->where('created_at', '<', now()->subDays(30));
    }

    public function redactionStrategy(): RedactionStrategy
    {
        return app(ReplaceContents::class)->replaceWith([
            'name' => '****',
            'email' => '****',
        ]);
    }
}
💡
You can also use MassRedactable instead of Redactable to make it more efficient to handle a lot of models at once.

Once you've set your strategy up, it's just a case of running:

php artisan model:redact

And let the package do it's work!

It's a fantastic package and Ash did a wonderful job at bringing it to life. There's a few more features worth exploring, which are all detailed on the Github repo, click below to view that!

GitHub - ash-jc-allen/redactable-models: A package that allows you to redact, obfuscate, or mask data in your Laravel models.
A package that allows you to redact, obfuscate, or mask data in your Laravel models. - ash-jc-allen/redactable-models