Vanhiep.NET - Chuyên gia Thiết kế Website & Ứng dụng

Xóa mềm trong laravel - Laravel Soft Delete

Hướng dẫn chi tiết Laravel Soft Delete

Bài viết "Xóa mềm trong Laravel - Laravel Soft Delete" sẽ hướng dẫn bạn cách triển khai tính năng Soft Delete (xóa mềm) trong các ứng dụng Laravel. Thay vì xóa vĩnh viễn dữ liệu khỏi cơ sở dữ liệu, Soft Delete cho phép bạn đánh dấu các bản ghi là đã xóa mà vẫn giữ chúng lại. Điều này cực kỳ hữu ích cho việc khôi phục dữ liệu, theo dõi lịch sử thay đổi hoặc đơn giản là cung cấp một lớp bảo vệ bổ sung chống lại việc xóa nhầm. Bạn sẽ tìm hiểu cách cấu hình, sử dụng và tương tác với các bản ghi đã xóa mềm trong Laravel một cách hiệu quả.

Bước 1 : Cài đặt Laravel Soft Delete

Mở file App\Providers\AppServiceProvider.php thêm vào dòng như sau

use Illuminate\Support\Facades\Schema; // add
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191); // add: default varchar(191)
    }
}

Trong model của bảng cần áp dụng ta thêm như sau.

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes; // add soft delete

class User extends Authenticatable
{
    use Notifiable,
        SoftDeletes;// add soft delete

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Nếu tạo bảng từ đầu bằng migrations thì ta thêm vào code như sau, còn bảng đã tạo rồi thì thêm bằng tay cột dữ liệu có tên delete_at với kiểu dữ liệu là timestamp nhé


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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes(); // add
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Bước 2 : Cách sử dụng Laravel Soft Delete

Ta vẫn sữ dụng tất cả các phương thức của model như bình thường Laravel sẽ tự động loại bỏ cột delete_at có giá trị khác rỗng.

Nếu muốn lấy tất cả các bản ghi, bao gồm cả các bản ghi đã xóa ta viết như sau.

App\User::withTrashed()->get();

Để lấy ra các bản ghi đã xóa ta viết như sau

App\User::onlyTrashed()->get();

Nếu đã xóa bản ghi rồi, giờ muốn quay lại, không xóa nữa ta viết như sau: 

App\User::withTrashed()->where('id', 1)->restore();

Để xóa vĩnh viễn 1 bản ghi ta viết như sau

App\User::withTrashed()->where('id', 1)->forceDelete();

Chúc các bạn thành công.