Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unique initials from first name & last name in Laravel Model Factory
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Illuminate\Support\Str;
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
static $existingInitials;
$existingInitials = $existingInitials ?: User::pluck('initials')->toArray();
$first_name = $faker->firstName;
$last_name = $faker->lastName;
$suffix = 0;
do {
$safeLastName = Str::ascii($last_name);
$initials = strtoupper(Str::ascii($first_name)[0]);
for ($i = 0; $i <= $suffix; $i++) {
if (! isset($safeLastName[$i])) {
$initials .= 'X';
continue;
}
$character = $safeLastName[$i];
if (in_array($character, [' ', '-', '\'', ''])) {
continue;
}
$initials .= strtoupper($character);
}
$suffix++;
} while (in_array($initials, $existingInitials));
$existingInitials[] = $initials;
return [
'initials' => $initials,
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.