phplaravellaravel-api

How to Generate unique usernames using Laravel


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;
    }

`


Solution

  • your issue generate from $request['firstname'.'lastname'], you are actually Concating keys of a request array though you want to Concat the value of 2 separate keys which means to use it like this $request['firstname'] and $request['lastname']. please change the below line

    $userName = $userObject->generateUserName($request['firstname'.'lastname']);
    

    with this

    $userName = $userObject->generateUserName($request['firstname'].$request['lastname']);