Dcat-admin给grid快速添加数据软删除功能 - 道与

/ 0评 / 0

定义行恢复操作和批量恢复操作

app\Admin\Actions\BatchRestore.php

app\Admin\Actions\Restore.php

相关文件
<?php

namespace App\Admin\Actions;

use Dcat\Admin\Grid\BatchAction;
use Illuminate\Http\Request;

class BatchRestore extends BatchAction
{
    protected $title = '恢复';

    protected $model;

    // 注意构造方法的参数必须要有默认值
    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    public function handle(Request $request)
    {
        $model = $request->get('model');

        foreach ((array) $this->getKey() as $key) {
            $model::withTrashed()->findOrFail($key)->restore();
        }

        return $this->response()->success('已恢复')->refresh();
    }

    public function confirm()
    {
        return ['确定恢复吗?'];
    }

    public function parameters()
    {
        return [
            'model' => $this->model,
        ];
    }
}
<?php

namespace App\Admin\Actions;

use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;

class Restore extends RowAction
{
    protected $title = '恢复';

    protected $model;

    // 注意构造方法的参数必须要有默认值
    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    public function handle(Request $request)
    {
        $key = $this->getKey();
        $model = $request->get('model');

        $model::withTrashed()->findOrFail($key)->restore();

        return $this->response()->success('已恢复')->refresh();
    }

    public function confirm()
    {
        return ['确定恢复吗?'];
    }

    public function parameters()
    {
        return [
            'model' => $this->model,
        ];
    }
}

定义统一调用方法

定义一个父操作类,例如:BaseAdminController ,其中填入 addRestore方法:

/**
     * 添加回收站功能.
     *
     * @return void
     */
    public static function addRestore(&$grid, $model)
    {
        'trashed' == request('_scope_') && $grid->column('deleted_at', '删除时间');
        $grid->filter(
            function (Grid\Filter $filter) {
                $filter->scope('trashed', '回收站')->onlyTrashed();
            }
        );

        $grid->actions(
            function (Grid\Displayers\Actions $actions) use ($model) {
                if ('trashed' == request('_scope_')) {
                    $actions->append(new Restore($model));
                }
            }
        );

        $grid->batchActions(
            function (Grid\Tools\BatchActions $batch) use ($model) {
                if ('trashed' == request('_scope_')) {
                    $batch->add(new BatchRestore($model));
                }
            }
        );
    }

使用效果

use App\Models\Account as Model;//传参需要
...

//需要添加软删除的grid方法里添加:
self::addRestore($grid, Model::class);

示例图片

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注