How to use Soft Delete in Laravel

I will explain you step by step implementation of how to use soft delete in laravel project. you have to of SoftDeletes for backup  in laravel.

This tutorial provides an example of how to use SoftDeletes in laravel.An example shows how softdelete can be defined in a model.You can use soft delete  Laravel 6,Laravel 7,Laravel 8, Laravel 9, Laravel 10.

Step 1.How to use soft delete in laravel application?
Example migration In laravel
php artisan make:migration create_posts_table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostTable extends Migration
{
     public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->softDeletes();
            $table->timestamps();
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

?>

Now you can run migration:

php artisan migrate

Ok You can find deleted_at column in your posts table and you have also model should look like below examples:

Step: 2 how to soft delete add in Post Model

app\Models\Post.php
<?php

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,SoftDeletes;
    
    protected $fillable = ['item','description'];
    
    protected $dates = ['deleted_at'];
    
    
}
Step 3 : Delete Record Soft Delete
$id = 1;
$post = Post::find($id);
$post->delete();
Step 4 : Get Soft Deleted Data
$id = 1;
$post = Post::withTrashed()->get();

I hope this tutorial can help you…

Leave a Reply

Your email address will not be published. Required fields are marked *