Recursive function example code PHP Laravel

The function which is called itself is a recursive function. Here we have an example code of recursive function which is used to create the username which is called itself till it does not get the unique username for a user while registration process.

Answers 1
  • Recursive function in Laravel to generate unique username

    public function generateUserName($name){
        $username = Str::lower(Str::slug($name));
        if(User::where('username', '=', $username)->exists()){
            $uniqueUserName = $username.'-'.Str::lower(Str::random(4));
            $username = $this->generateUserName($uniqueUserName);
        }
        return $username;
    }
    
    0
  • Back to code snippet queries related laravel