Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Generate Password Laravel Package

naif/generate-password

A Laravel/PHP package for generating secure, customizable passwords. Quickly create random passwords with configurable length and character sets, ideal for user onboarding, admin tools, and testing workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

First, correct the mental model. naif/generate-password is not a general-purpose Laravel password helper despite the package name — it is a single Laravel Nova form field (Naif\GeneratePassword\GeneratePassword) plus a small Vue component that adds a "generate" button beside a password input. If you're not running Nova, there is nothing to install. Read the source and lift the pattern instead.

Where to look first — the source, not the README. The README is a screenshot and a composer require line. Open two files before you wire anything up:

  1. The field class in src/ — check how it registers the Vue component, whether it exposes length/charset options, and whether any generation happens in PHP.
  2. The .vue component in resources/js/ — check whether it calls crypto.getRandomValues or Math.random, and whether the value lands in the DOM as an attribute, a title, or Vue state.

Those two answers determine your leak surface and whether the thing is safe to ship next to authentication at all.

Install (only on a Nova 1.x/2.x-era stack):

composer require naif/generate-password

First use case — the only one this package serves well. An internal operator provisioning an account in a Nova resource wants a random temporary credential instead of typing Password123. Wire it write-only, required on create, nullable on update:

use Naif\GeneratePassword\GeneratePassword;

public function fields(Request $request)
{
    return [
        // ...
        GeneratePassword::make('Password')
            ->onlyOnForms()
            ->creationRules(['required', 'string', 'min:12'])
            ->updateRules(['nullable', 'string', 'min:12'])
            ->help('Copy this now — it cannot be retrieved after save.'),
    ];
}

The realistic first move: vendor it. Copy the field class and the Vue component into App\Nova\Fields\RandomPassword, strip what you don't use, and drop the Composer requirement. You keep the UX, you own the code, and you remove a 2019 dependency from your upgrade path. Roughly half a day including a test that the field renders and the submitted value passes rules. If you'd rather not carry the Vue component, back the field with Laravel's own generator server-side:

use Illuminate\Support\Str;

$password = Str::password(length: 20, symbols: true, spaces: false); // Laravel 10+

On Laravel 9 and below, write the equivalent with random_int — index into a charset with random_int(0, strlen($charset) - 1) rather than using modulo, and consider omitting l, I, O, 0, 1 since operators read these aloud and retype them.

Implementation Patterns

Pattern 1 — asymmetric validation rules. The password field is write-only by design. Always pair onlyOnForms() with required on create and nullable on update, so editing an unrelated attribute doesn't blank the credential. Use Password::defaults() for policy and keep the generation feature separate from policy enforcement:

RandomPassword::make('Password')
    ->onlyOnForms()
    ->creationRules(['required', 'string', Password::defaults()])
    ->updateRules(['nullable', 'string', Password::defaults()])
    ->help('Copy this now — it cannot be retrieved after save.');

Pattern 2 — generate client-side, validate server-side, never display from PHP. If you attach the generated string to the field's meta in a resolveUsing/fillUsing callback, the plaintext is in the Nova response JSON: browser network tab, Telescope, Debugbar, request-logging middleware, APM. Prefer generation in the browser via crypto.getRandomValues in the Vue component, and let the server enforce rules on submit. The browser proposes; Password::defaults() disposes.

Pattern 3 — pair the button with a lifecycle. A generated password that becomes a permanent shared secret is worse than a weak one because it looks safe. Two additions carry most of the value:

$user->forceFill([
    'password' => Hash::make($password),
    'must_change_password' => true,
])->save();

activity()->performedOn($user)
    ->withProperties(['generated_by' => $request->user()->id])
    ->log('provisioned credential');

On login, redirect to a forced change-password screen while must_change_password is true. A dozen lines converts a convenience feature into something an auditor won't flag.

Pattern 4 — reuse the generator outside Nova. The same charset/length logic is useful in seeders, test factories, and artisan commands (php artisan user:provision). Extract it to App\Support\PasswordGenerator (or just call Str::password()) so credentials aren't reachable only through a Vue button — QA and CI will want it.

Pattern 5 — combine the button with the model's hashed cast. Nova's password field stores nothing itself; the hash comes from your model. On Laravel 10+ use the hashed cast and don't also call Hash::make() in a mutator, or you'll double-hash. If you're on an older version, guard the empty-string path explicitly:

protected function password(): Attribute
{
    return Attribute::make(
        set: fn ($value) => filled($value)
            ? Hash::make($value)
            : ($this->attributes['password'] ?? null),
    );
}

Pattern 6 — test the field, not the randomness. Feature-test the Nova field: it renders on the create form, is absent from index/detail, and the submitted value passes the same rules the server enforces. Unit-test the generator by shape only — length, charset membership, at least one character from each required class. Never assert specific output.

Gotchas and Tips

Compatibility is the dominant risk, and it fails silently. A March 2019 release targets Nova 1.x/2.x, Laravel 5.7–5.8, PHP 7.x, and Vue 2. On Nova 4/5 the PHP class may autoload and register cleanly while the Vue component never mounts. The field renders, the button does nothing, no error appears anywhere. Your compatibility spike must click the button and inspect the DOM, not just boot the panel.

The password is gone after save. Nova's password field is write-only; only the hash persists. If an operator forgets to copy before saving, the account is unrecoverable and your "convenience" feature filed a support ticket. Put the instruction in help() and, if you vendored the component, add copy-to-clipboard.

Verify the option API against the source. The field predates most of the fluent Nova API you'd assume. ->onlyOnForms(), ->creationRules(), and ->help() are core Nova methods and safe. Any package-specific length/charset options are undocumented — read the class rather than guessing at method names.

Guard the empty-string update path. With updateRules('nullable'), an edit form submitted without touching the password can write '' or null into the attribute. On Laravel 10+ the hashed cast will hash an empty string without complaint; on older versions a naive Hash::make($value) mutator does the same. Guard with filled() as shown above, and settle on one hashing mechanism.

Assume your logging stack is watching. Telescope, Debugbar, request-logging middleware, and APM capture request payloads by default. A plaintext password submitted through the Nova form lands in all of them. Redact password / password_confirmation in TelescopeServiceProvider's hideRequestParameters and in any custom middleware before you ship this.

Password::defaults() won't save you from itself. ->uncompromised() makes an outbound call to Have I Been Pwned on every validation and fails on air-gapped or rate-limited environments — largely a no-op for a freshly generated random string anyway. Reserve it for user-chosen passwords. Also check that your rules and your generator agree: a 12-character generated string with symbols enabled can still contain zero symbols and fail ->symbols(). Guarantee one character from each required class, then shuffle.

Randomness is the security review. A generator producing plausible-looking strings from mt_rand or Math.random is worse than no button, because it manufactures false confidence. If the source uses anything other than random_int, Str::password(), or crypto.getRandomValues, replace it — this code sits next to authentication and will be read that way during any audit or pentest.

Treat upgrades as a checkpoint. If you adopt upstream rather than vendoring, add "verify the generate button still works" to your Nova upgrade checklist. With 18 stars, zero dependents, and no maintainer since 2019, no one upstream will notice when it breaks — and neither will you, until an operator files a ticket.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings