Skip to content
全部文档

恢复操作

简介

Filament 包含一个用于恢复已 软删除 的 Eloquent 记录的操作。点击触发按钮后,会弹出模态框要求用户确认。你可以这样使用:

php
use Filament\Actions\RestoreAction;

RestoreAction::make()
恢复操作模态框恢复操作模态框

或者,若要将其添加为表格批量操作,以便用户选择要恢复的行,请使用 Filament\Actions\RestoreBulkAction

php
use Filament\Actions\RestoreBulkAction;
use Filament\Tables\Table;

public function table(Table $table): Table
{
    return $table
        ->toolbarActions([
            RestoreBulkAction::make(),
        ]);
}

恢复后重定向

你可以使用 successRedirectUrl() 方法在表单提交后设置自定义重定向:

php
use Filament\Actions\RestoreAction;

RestoreAction::make()
    ->successRedirectUrl(route('posts.list'))

TIP

除了 $record 之外,successRedirectUrl() 函数还可以注入各种实用工具作为参数。

自定义恢复通知

记录成功恢复后,会向用户发送通知,提示操作成功。

若要自定义该通知的标题,请使用 successNotificationTitle() 方法:

php
use Filament\Actions\RestoreAction;

RestoreAction::make()
    ->successNotificationTitle('User restored')

TIP

除了允许静态值外,successNotificationTitle() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。

你可以使用 successNotification() 方法自定义整个通知:

php
use Filament\Actions\RestoreAction;
use Filament\Notifications\Notification;

RestoreAction::make()
    ->successNotification(
       Notification::make()
            ->success()
            ->title('User restored')
            ->body('The user has been restored successfully.'),
    )

TIP

除了允许静态值外,successNotification() 方法也接受一个函数来动态计算值。你可以将各种实用工具作为参数注入该函数。

若要完全禁用通知,请使用 successNotification(null) 方法:

php
use Filament\Actions\RestoreAction;

RestoreAction::make()
    ->successNotification(null)

生命周期钩子

你可以使用 before()after() 方法在记录恢复前后执行代码:

php
use Filament\Actions\RestoreAction;

RestoreAction::make()
    ->before(function () {
        // ...
    })
    ->after(function () {
        // ...
    })

TIP

这些钩子函数可以注入各种实用工具作为参数。

提升恢复批量操作的性能

默认情况下,RestoreBulkAction 会先将所有 Eloquent 记录加载到内存中,再逐条循环恢复。

若要恢复大量记录,可使用 chunkSelectedRecords() 方法每次获取较少数量的记录,从而降低应用的内存占用:

php
use Filament\Actions\RestoreBulkAction;

RestoreBulkAction::make()
    ->chunkSelectedRecords(250)

Filament 在恢复前将 Eloquent 记录加载到内存,有两个原因:

  • 允许在恢复前使用模型策略对集合中的单条记录进行授权(例如使用 `authorizeIndividualRecords('restore')`)。
  • 确保恢复记录时会触发模型事件,例如模型观察者中的 `restoring` 和 `restored` 事件。

若不需要单条记录的策略授权和模型事件,可以使用 fetchSelectedRecords(false) 方法。这样在恢复前不会将记录加载到内存,而是用单次查询恢复:

php
use Filament\Actions\RestoreBulkAction;

RestoreBulkAction::make()
    ->fetchSelectedRecords(false)