earmsby's avatar

Encrypt account's tax ID but show last 4 digits in view

I have a model Account with various fields:

I've just added that last 'tax_id' and I'm creating the migration to add the new field to the database.

I'm hoping to store the tax_id field hashed (like passwords in the Users table) but then will need to show something like this in the view for the account info:

Tax ID: *--1234

I'm sure this is fairly common, but would appreciate guidance on how to set up the model, the migration and the view.

Thanks for any suggestions on best approach.

0 likes
3 replies
LaryAI's avatar
Level 58

Certainly! To securely store a tax ID but display only the last 4 digits in your Laravel app, you have two main concerns:

  1. Properly encrypting the tax ID (not hashing, since you need to retrieve and partially display it)
  2. Displaying only the last 4 digits in your view

Let's walk through each step.


1. Migration: Add the tax_id Field

Use php artisan make:migration add_tax_id_to_accounts_table and in the migration file:

public function up()
{
    Schema::table('accounts', function (Blueprint $table) {
        $table->text('tax_id')->nullable(); // Use text as encrypted strings can be long
    });
}

Run php artisan migrate.


2. Model: Encrypt and Decrypt Automatically

You want to encrypt the tax ID when saving to the database, and decrypt it when accessing via Eloquent.

Add tax_id to the $casts property in your Account model using the built-in encrypted cast in Laravel (Laravel 9+):

protected $casts = [
    // ... your other casts ...
    'tax_id' => 'encrypted',
];

3. Model: Accessor for Last 4 Digits (Masked Version)

Add an accessor to get the masked tax ID for display:

public function getMaskedTaxIdAttribute()
{
    if (!$this->tax_id) {
        return null;
    }

    $taxId = $this->tax_id; // This will be automatically decrypted
    return str_repeat('*', max(0, strlen($taxId) - 4)) . substr($taxId, -4);
}

4. Usage in the Controller or View

When displaying the masked tax ID in your Blade view:

Tax ID: {{ $account->masked_tax_id }}

Example output: *****1234


5. Optional: Storing Tax ID

To set the tax ID, simply assign it as plain text, and Laravel will encrypt it:

$account->tax_id = '123456789';
$account->save();

6. Security Note

  • Don't hash the tax ID if you need to display any part of it; use encryption so you can retrieve it when needed.
  • The encrypted cast stores data encrypted using your app's APP_KEY and Laravel's underlying encryption implementation.

Summary

  1. Add tax_id as a text column.
  2. Use Laravel's encrypted cast on the tax_id model field.
  3. Define a getMaskedTaxIdAttribute accessor.
  4. Use $account->masked_tax_id in your views.

earmsby's avatar

I used the accessor shown in Larry AI's answer and that seems to work.

Please or to participate in this conversation.