Skip to content

Instantly share code, notes, and snippets.

@depsimon
Created July 18, 2019 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save depsimon/d26d2809b9269fbe0f7f82b9d2ae2fc6 to your computer and use it in GitHub Desktop.
Save depsimon/d26d2809b9269fbe0f7f82b9d2ae2fc6 to your computer and use it in GitHub Desktop.
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