Certainly! To securely store a tax ID but display only the last 4 digits in your Laravel app, you have two main concerns:
- Properly encrypting the tax ID (not hashing, since you need to retrieve and partially display it)
- 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',
];
- If on Laravel <9: use get/set accessors and the
encrypt()/decrypt()helpers.
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
encryptedcast stores data encrypted using your app'sAPP_KEYand Laravel's underlying encryption implementation.
Summary
- Add
tax_idas atextcolumn. - Use Laravel's
encryptedcast on thetax_idmodel field. - Define a
getMaskedTaxIdAttributeaccessor. - Use
$account->masked_tax_idin your views.