Im using Laravel 5.4 and I'm using a slug to look-up users in database.
Im adding first_name
and last_name
to the slug, and if there is a user with the same name, appending a number (increment it if there is more than one with same name) to the end ex John.doe.3
.
This is what I have in RegisterController.php
protected function create(array $data)
{
// Set the may be name
$maybe_slug = strtolower($data['first_name'] . '.' . $data['last_name']);
// Check if there is another one in the DB with the same name
$user = User::where('slug', 'like', $maybe_slug . '%')->orderBy('created_at', 'desc')->first();
if($user){
$split_user_name = explode('.', $user->slug);
$number = isset($split_user_name[2]) ? $split_user_name[2] : null;
if(isset($number)){
$slug = $maybe_slug . '.' . ($number + 1);
}elseif($user->slug == $maybe_slug){
$slug = $maybe_slug . '.2';
}
}else{
$slug = $maybe_slug;
}
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'slug' => $slug,
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
This is how RegisterController
looks like un-edited (GitHub)
Can I do this in a better way?