I am trying to generate unique usernames for users upon registration using laravel. I want to include both the first name and the last name. If I use only the first or last name it works, but if I try both, it enters a blank value to the database. Please Help.
Here is my code: Auth Controller
`
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname'=>'required|max:191',
'lastname'=>'required|max:191',
'phone'=>'required',
'email'=>'required|email|max:191|unique:users,email',
'password'=>'required|min:6',
]);
if($validator->fails())
{
return response()->json([
'validation_errors'=>$validator->messages(),
]);
}
else
{
$userObject = New User;
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
$user = User::create([
'firstname'=>$request->firstname,
'lastname'=>$request->lastname,
'phone'=>$request->phone,
'email'=>$request->email,
'password'=>Hash::make($request->password),
'username'=>$userName,
]);
$token = $user->createToken($user->phone.'_Token')->plainTextToken;
return response()->json([
'status'=>200,
'username'=>$user->firstname,
'token'=>$token,
'message'=>'Registered Successfully',
]);
}
}
`
The User Model
`
public function generateUserName($firstname){
$username = Str::lower(Str::slug($firstname));
if(User::where('username', '=', $username)->exists()){
$uniqueUserName = $username.'-'.Str::lower(Str::random(5));
$username = $this->generateUserName($uniqueUserName);
}
return $username;
}
`
CodePudding user response:
please change
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
to this
$userName = $userObject->generateUserName($request['firstname'].$request['lastname']);