Ricardo Nolan
3 min readJan 17, 2023

--

In today’s digital age, protecting personal data is more important than ever. With the introduction of the General Data Protection Regulation (GDPR) in Europe and similar policies in the United States, it’s crucial for businesses to ensure that they are handling customer data in a secure and compliant way.

One way to do this is by masking sensitive information, such as email addresses and phone numbers, by default. This means that the information is replaced with a string of asterisks, making it unreadable to anyone without the proper permissions.

In the PHP framework Laravel, it’s easy to implement this functionality by using a trait. A trait is a reusable piece of code that can be added to any class, in this case, the customer model. By using a trait, we can keep the code organised and maintain a single source of truth for masking and unmasking data.

First, we create the trait called “Maskable” and place it in the app/Traits directory. In this trait, we define two methods: one to mask a field and one to unmask a field, while logging the user ID of who unmasked it.

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait Maskable
{
/**
* Mask the specified field.
*
* @param string $field
* @return void
*/
public function mask($field)
{
$this->$field = str_repeat("*", strlen($this->$field));
}

/**
* Unmask the…

--

--

Ricardo Nolan

I write code like it's poetry and test it like it's my enemy