Xây dựng trang quản trị laravel 9 với Laravel-admin bằng demo 1 trang blog cá nhân phần 6 Xoá mềm và Action

Xây dựng trang quản trị laravel 9 với Laravel-admin bằng demo 1 trang blog cá nhân phần 6 Xoá mềm và Action

Trong quản trị đôi khi chúng ta muốn 1 thùng rác chứa các bài viết bỏ đi mà không muốn xoá hẳn tránh trường hợp mà lúc sau bạn không muốn xoá bài viết đó nữa .Vậy chúng ta sẽ thêm xoá mềm vào trong quản trị 

 Trong file migrate chúng ta cần thêm 

$table->softDeletes();

vào trong file migrate demo database/migrations/2022_11_10_071256_create_posts_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title',500);
            $table->string('slug',500);
            $table->string('description',1000)->nullable();
            $table->longText('content')->nullable();
            $table->integer('category_id');
            $table->string('thumbnail')->nullable();;
            $table->string('video')->nullable();
            $table->tinyInteger('type')->comment('type của bài viết 1 là bài viết ,2 là video ,3 là ảnh ')->default(1);
            $table->tinyInteger('status')->comment('trạng thái của bài viết 0 là không hiển thị 1 là hiển thị')->default(1);
            $table->timestamps();
            $table->softDeletes();
        });
    }

Ở đây chúng ta đã thêm cột delete_at vào trong mysql .Trong phần model 


namespace App\Models;

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

class Post extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $fillable=['title','slug','description','content','category_id','thumbnail','video','type','status','postrelate'];
    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id');
    }

    public function getPostrelateAttribute($value)
    {
        return explode(',', $value);
    }

    public function setPostrelateAttribute($value){
        $this->attributes['postrelate'] = implode(',', $value);
    }

Bạn dùng use SoftDeletes để xoá mềm

Tiếp theo trong laravel admin 

php artisan admin:action Post\Restore --grid-row --name=Restore

Chúng ta sẽ có file trong app/Admin/Actions/Post/Restore.php chúng ta code như sau :

namespace App\Admin\Actions\Post;

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

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

    public function handle(Model $model)
    {
        // $model ...
        $model->restore();
        return $this->response()->success('Restore thành công.')->refresh();
    }
    // hỏi trươc khi xoá
    public function dialog()
    {
        return $this->confirm('Bạn có muốn restore lại dữ liệu');
    }
}

Bây giờ chúng ta cần hiển thị Danh sách các post bị xoá .

Đường link truy cập bài post bị xoá có dạng : http://127.0.0.1:8000/admin/posts?&_scope_=trashed

 protected function grid()
    {
        $grid = new Grid(new Post());
        $grid->model()->orderByDesc('id');
        $grid->filter(function (Grid\Filter $filter){
            $filter->disableIdFilter();
            $filter->like('title','Tiêu đề');
            $filter->scope('trashed','Thùng rác')->onlyTrashed();
        });
        if(request('_scope_') =='trashed') {
            $grid->batchActions(function (Grid\Tools\BatchActions $batchActions) {
                $batchActions->add(new BatchRestore());
                $batchActions->disableDelete();
            });
        }
        $grid->actions(function (Grid\Displayers\Actions $actions){
            if(! request('_scope_') =='trashed')
            {
                $actions->add(new Replicate());
                $actions->add(new ViewPost());
            }else{
                $actions->add(new Restore());
                $actions->add(new Delete());
            }
        });
......................................

Ở đây ta thấy 

$filter->scope('trashed','Thùng rác')->onlyTrashed();

Có chức năng lọc các bài viết bị loại bỏ

Tiếp theo ta thêm action vừa code ở trên vào 

$grid->actions(function (Grid\Displayers\Actions $actions){
            if(! request('_scope_') =='trashed')
            {
                $actions->add(new Replicate());
                $actions->add(new ViewPost());
            }else{
                $actions->add(new Restore());
                $actions->add(new Delete());
            }
        });

Vậy là xong phần delete từng phần tử 

Giờ đến phần Batch Restore 

Chúng ta tạo action batch với command sau :

php artisan admin:action Post\RestoreAll --grid-batch --name=RestoreAll

Trong file app/Admin/Actions/Post/RestoreAll.php  chúng ta code như sau :


namespace App\Admin\Actions\Post;

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

class RestoreAll extends BatchAction
{
    public $name = 'RestoreAll';

    public function handle(Collection $collection)
    {
        foreach ($collection as $model) {
            $model->restore();
        }

        return $this->response()->success('Success message...')->refresh();
    }
    public function dialog()
    {
        return $this->confirm('Bạn muốn restore all');
    }

}

Tiếp theo chúng ta cần thêm batch action như sau :

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

Vậy là xong phần Soft Delete thông qua việc restore lại dữ liệu đã xoá