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





