Protect Sensitive Data Instantly with Str::mask() in Laravel
🚀 The Real Problem
In real applications, we often need to display data without exposing everything:
- Email addresses
- Phone numbers
- Aadhaar / PAN / IDs
- Credit card numbers
Many developers write custom logic like:
$email = substr($email, 0, 3) . '****' . substr($email, -5);
This is:
- error-prone
- hard to reuse
- inconsistent
Laravel gives you a clean solution.
🎯 The Laravel Way: Str::mask()
use Illuminate\Support\Str;
Str::mask('john.doe@gmail.com', '*', 3, 5);
Result:
joh*****gmail.com
That’s it. Clean and readable.
🧠 Real-World Examples
✔ Mask Phone Number
Str::mask('9876543210', '*', 2, 6);
Result:
98******10
✔ Mask Email Username Only
$email = Str::of('john.doe@gmail.com')
->before('@')
->pipe(fn ($name) => Str::mask($name, '*', 1))
. '@gmail.com';
Result:
j******@gmail.com
Perfect for invoices and profiles.
✔ Mask Card Number
Str::mask('4111222233334444', '*', 4, 8);
Result:
4111********4444
🧩 Blade Example
{{ Str::mask($user->phone, '*', 2, 6) }}
No helper functions.
No custom logic.
💡 Why Str::mask() Is So Useful
- Built-in & reliable
- Avoids custom string hacks
- Keeps UI consistent
- Improves security instantly
- Perfect for GDPR-style data exposure rules