Generate password by button in blade file

Viewed 38

inside Laravel Blade file I'm trying to achieve a simple password generator button that inputs generated password in field

Button:

<a class="btn btn-xs btn-success" onClick=generatePass()>Generate Me</a>


<script>
    function generatePass() {
        var hashed_random_password = Hash::make(str_random(12));
            $('#password').val(hashed_random_password);
        }
                
</script>

The button works, tested by using console.log('button clicked'); But hashing doesn't work, I need to achieve generating a hashed password and inputs it value directly into the password form field

Any suggestion how to get that simply in blade without invloving the routes and controller files?

3 Answers
<a class="btn btn-xs btn-success" onClick=generatePass()>Generate Me</a>

<script>
  function generatePass() {
    var pass = '';
    var str='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    +  'abcdefghijklmnopqrstuvwxyz0123456789@#$';

   for (let i = 1; i <= 8; i++) { 
      var char = Math.floor(Math.random()* str.length + 1); 
            pass += str.charAt(char) 
        } 
  $('#password').val(pass);
    }
            

Now at your laravel controller Hash this password.

You can't use Hash::make in javascript, that is a PHP/Laravel method.

You can use something like this to generate a random hash:

function generatePass() {
    // change 12 to the length you want the hash
    let randomPasswordHash = (Math.random() + 1).toString(36).substring(12);

    $('#password').val(randomPasswordHash);
}

blade:

<button onclick="generateRandomPassword()">Generate Password</button>
<h2 id="password"></h2>

<script>
    function generateRandomPassword() {
        $.ajax({
            url: '/generate-password',
            success: function (data) {
                $('#password').html(data);
            }
        });
    }
</script>

route/controller:

Route::any('/generate-password', function () {
    return Hash::make(Str::random(12)); 
});
Related