Have you ever run into a situation where you need to create a displayable username from email address in Laravel? Maybe during registration or for profile displays? I know I have! Extracting a username from an email can be handy, but we need to do some cleanup to make it look nice.
In this post, we’ll explore a simple function we can use to generate a displayable username from an email address using Laravel’s awesome Str
class.
And if you ever need to calculate a user’s age from their birthday in Laravel, check out How To Easily Calculate Age From Birthday in Laravel with Carbon
Laravel Str Class
Laravel’s Str
class offers a bunch of useful methods for working with strings. Here, we’ll leverage a few of them to transform an email address into a username.
Generate Displayable Username From Email
Let’s jump into the code and see how this magic happens:
function generateUsername (string $email) {
return Str::of($email)
->before('@') // Grab everything before the "@" symbol
->replace('/[0-9]+/', '') // Remove any numbers
->replace('/\.+/', ' ') // Replace consecutive dots with a single space
->headline(); // Capitalize the first letter of each word
}
echo generateUsername('harry.potter@gmail.com'); // Outputs: Harry Potter
Let’s break down what each bit of code does:
Str::of($email)
: We start by converting the email address to aStr
object usingStr::of()
.->before('@')
: This method grabs the part of the email address that comes before the “@” symbol. This is typically the username portion.->replace('/[0-9]+/', '')
: Regular expressions come in handy here! This line removes any sequences of numbers from the username usingreplace()
. We don’t want usernames like “john.doe123”.->replace('/\.+/', ' ')
: Another helpfulreplace()
method. This one targets consecutive dots (periods) and replaces them with a single space. This takes care of emails like “jo.anna.smith@…” and turns them into “Jo Anna Smith”.->headline()
: Finally, we use theheadline()
method to capitalize the first letter of each word in the username. This gives us a username that looks presentable, like “Harry Potter”.
Conclusion
By leveraging the Str
class and its powerful methods, we can easily create a function to generate displayable usernames from email addresses. This can be a handy tool for various user management functionalities within your application.