9 months ago

Loop in Controller to Set Unique Username

Posted 9 months ago by WallyJ

When creating a new user, the system will create a unique username automatically using the user's first name and last four digits of their phone number, then check to make sure that username doesn't exist already in the user db.

In the event that this username exists (ie "Roger1234"), I want the controller to simply add 1 to the number (ie "Roger1235") and then check that username against the existing user db.

I'm not sure how to have it loop back and keep trying until it is successful. Here's what I have so far:

//Testing Username Creation
        $names = explode(' ', Input::get('name'), 2);
        $firstname = $names[0];
        $phonenumber = Input::get('phone');
        $phonelast4 = substr ($phonenumber, -4);
        $newusername = $firstname.$phonelast4;
        $usercheck = DB::table('users')->where('username', '=', $newusername)->first();
        if ($usercheck === null) {
           // user doesn't exist
           echo "The username DOES NOT exist";
        else {
            echo "That username ALREADY EXISTS";

After the Else, how do I tell it to add 1 to the $phonelast4 and then have it check again? Thanks!

Please sign in or create an account to participate in this conversation.