Tricks

Hashing password fields and handling password updates

Jun 10, 2022
Dan Harrin
Form builder, Admin panel

You have a password field:

use Filament\Forms\Components\TextInput;
 
TextInput::make('password')
->password()

And you wanted to hash the password when the form is submitted:

use Filament\Forms\Components\TextInput;
use Illuminate\Support\Facades\Hash;
 
TextInput::make('password')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))

But you don't want to overwrite the existing password if the field is empty:

use Filament\Forms\Components\TextInput;
use Illuminate\Support\Facades\Hash;
 
TextInput::make('password')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))

However, you want to require the password to be filled on the Create page of an admin panel resource:

use Filament\Forms\Components\TextInput;
use Filament\Pages\Page;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Hash;
 
TextInput::make('password')
->password()
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))
->required(fn (Page $livewire): bool => $livewire instanceof CreateRecord)
avatar

Nice one :) But there's a small typo, the last line should be:

->required(fn (Page $livewire) => ($livewire instanceof CreateRecord))
👍 1
avatar

Thanks, I fixed it :)