laravel-admin 软删除

本文详细介绍了在Laravel框架中实现软删除功能的步骤,包括在数据库添加删除时间字段、在模型中使用SoftDeletes特性、通过范围过滤器展示被软删除的数据、在控制器中添加恢复操作以及实现批量恢复。特别强调了从回收站进行的删除是彻底删除。

1、在数据库添加“deleted_at”删除时间字段
2、在model添加use SoftDeletes;
3、前提config/admin.php文件中的
‘grid_action_class’ => \Encore\Admin\Grid\Displayers\DropdownActions::class,

没有改变操作按钮,否则报错

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
}

3、删除信息查看,使用model-grid的范围过滤器实现

$grid->filter(function () {

    // 范围过滤器,调用模型的`onlyTrashed`方法,查询出被软删除的数据。
    $filter->scope('trashed', '回收站')->onlyTrashed();

});

4、点击回收站按钮就能查询出删除的数据,注意:如果从回收站进行删除就是彻底删除
5、恢复回收站数据操作有两种,(1)单独恢复(2)批量恢复

  • 单独恢复

按照下面的方法,我们可以在回收站中的每一行数据加上一个恢复操作,方便恢复数据
先定义操作类 app/Admin/Actions/Post/Restore.php

<?php

namespace App\Admin\Actions\Post;

use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;

class Restore extends RowAction
{
    public $name = '恢复';

    public function handle(Model $model)
    {
        $model->restore();

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

    public function dialog()
    {
        $this->confirm('确定恢复吗?');
    }
}

在controller中的grid中添加

use App\Admin\Actions\Post\Restore;

$grid->actions(function ($actions) {

    if (\request('_scope_') == 'trashed') {
        $actions->add(new Restore());
    }

});
  • 批量恢复

先定义操作类app/Admin/Actions/Post/BatchRestore.php:

<?php

namespace App\Admin\Actions\Post;

use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;

class BatchRestore extends BatchAction
{
    public $name = '恢复';

    public function handle(Collection $collection)
    {
        $collection->each->restore();

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

    public function dialog()
    {
        $this->confirm('确定恢复吗?');
    }
}

在controller中的grid中添加

use App\Admin\Actions\Post\BatchRestore;

$grid->batchActions(function ($batch) {

    if (\request('_scope_') == 'trashed') {
        $batch->add(new BatchRestore());
    }

});

注意:如果从回收站进行删除就是彻底删除
总结laravel-admin中的文章内容

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值