Laravel 8 Soft Delete Example

In this example we learn Laravel 8 Soft Delete Example. Also we learn get soft deleted data, restore soft deleted data, force delete soft data. I will explain you step by step implementation of soft delete data in Laravel application. we have to use soft delete for safety and backup in Laravel.

deleted_at column on the table that be default will be null and when we remove then it will place present timestamp, Laravel Model all times fetch that record have only deleted_at = null.

How to use in our project, we first when you create table migration then you have to add softDeletes(). you can see such as follow example of migration.

Read Also :  Razorpay Payment Gateway Integration in Laravel

Laravel 8 Soft Delete Example

Step 1 : Create Migration

Create migration of Demos table.

<?php

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

class CreateDemoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('demo', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('username');
            $table->string('password');
            $table->softDeletes();
            $table->timestamps();
        });  
    }

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

Step 2: Create Model

<?php

namespace App\Models;

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

class Demo extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $dates = ['deleted_at'];
    protected $table = 'demo';
    protected $fillable = ['name','email','username','password'];
}

Step 3: Soft Delete data

In this step to create soft delete data in route.

<?php

use Illuminate\Support\Facades\Route;
use App\Models\Demo;


  Route::get("softdelete", function(){
     Demo::find(2)->delete();
  });

Step 4: Get Deleted Data

In this step we get soft deleted data in laravel.

Route::get("get_deleted_record", function(){
   return Demo::onlyTrashed()->get();
});

Step 5: Restore Soft Deleted Data

In this step we restore soft deleted data in laravel.

Route::get("restore", function(){
   Demo::withTrashed()->restore();
});

Step 6: forceDelete Data

In this step we finally delete of soft deleted data in laravel.

Route::get("forcedelete", function(){
   Demo::withTrashed()->find(1)->forceDelete();
});

 

Read Also :  Laravel 8 View Render Example

I hope you understand of Soft Delete in laravel…