Skip to content

Instantly share code, notes, and snippets.

@jlpellicer
Last active December 8, 2023 03:07
Show Gist options
  • Save jlpellicer/ee8fb0f2b040a8e966cde64fe115eaa8 to your computer and use it in GitHub Desktop.
Save jlpellicer/ee8fb0f2b040a8e966cde64fe115eaa8 to your computer and use it in GitHub Desktop.
Filament & Laravel add new reusable actions

Laravel 10 / Filament 3 / Livewire

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment