1- Create your action, your Laravel Action You can see that I alredy have a notification that handles the email where the new password is sent.
<?php
namespace App\Actions;
use App\Models\User;
use App\Notifications\NewPasswordNotification;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UpdateAndSendNewPasswordAction
{
public function execute(User $user): void
{
$new_password = Str::password(8);
$user->password = Hash::make($new_password);
$user->save();
$user->plain_password = $new_password;
$user->notify(new NewPasswordNotification($user));
}
}
2- In your Filament Model Resource, in this case App\Filament\Resources\UserResource.php
, I'll add a new button to the view form (Create, Edit and View) and a new action in the table view.
Edited for brevity, only included the Email field for reference:
In the action
I invoke my Action, along with the $user
that I want to change the password.
Forms\Components\TextInput::make('email')
->email()
->required(),
Forms\Components\Actions::make([
Forms\Components\Actions\Action::make('Send new password')
->action(function (User $user, UpdateAndSendNewPasswordAction $updateAndSendNewPasswordAction) {
$updateAndSendNewPasswordAction->execute($user);
})
])
3- In the table, it looks like this:
->actions([
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
Tables\Actions\Action::make('New password')
->action(function (User $user, UpdateAndSendNewPasswordAction $updateAndSendNewPasswordAction) {
$updateAndSendNewPasswordAction->execute($user);
})
])
There, so I reused the code I need to update and send the new password to a user and added the buttons where I need them.
Related links: https://laraveldaily.com/post/filament-add-custom-action-button-inside-form