Hidden Methods Beginner Since Laravel 9.x

Str::mask()

Mask a portion of a string with a repeated character — ideal for obscuring emails, phone numbers, or sensitive data.

Overview

Str::mask() replaces part of a string with a repeated character (default *). You specify a start index and optionally a length, just like substr().

Usage

use Illuminate\Support\Str;

// Mask from position 3 onward
Str::mask('[email protected]', '*', 3);
// 'tay***************'

// Mask from position 3, only 4 characters
Str::mask('[email protected]', '*', 3, 4);
// 'tay****example.com'

Use negative indices to mask from the end:

Str::mask('1234-5678-9012-3456', '*', -4);
// '1234-5678-9012-****'

// Mask the middle portion
Str::mask('[email protected]', '*', 3, -8);
// 'tay*******ple.com'

Real-World Example

Displaying partially-masked user data in account settings:

class User extends Model
{
    public function maskedEmail(): string
    {
        $local = Str::before($this->email, '@');
        $domain = Str::after($this->email, '@');

        return Str::mask($local, '*', 2) . '@' . $domain;
    }

    public function maskedPhone(): string
    {
        return Str::mask($this->phone, '*', 0, -4);
    }
}

When to Use

  • Displaying partially-hidden email addresses or phone numbers
  • Masking credit card numbers for display
  • Audit logs where full PII shouldn't be stored