Recursive function example code PHP Laravel

Updated at 08-Mar-2022, By samar

Recursive function example code PHP Laravel

Through many examples, we will learn how to resolve the "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.
  • 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;
    }
    

Back to code snippet queries related laravel