Laravel Add Soft Delete to Existing Table Example

By Hardik Savani January 23, 2023 Category : Laravel

Hi Developer,

This definitive guide, we will show you laravel add soft delete to existing table. I explained simply about how to add soft delete in existing table laravel. It's a simple example of laravel soft delete in existing table. I’m going to show you about laravel add soft delete to existing table.

If you want to add soft delete in the existing table with laravel then i will show you the following two things you need to do.

1. Create Migration and add deleted_at column using softDeletes() function.

2. Use Illuminate\Database\Eloquent\SoftDeletes facade in model and use SoftDeletes class.

So, let's see the following step to adding soft delete to an existing table in laravel.

Step 1: Add deleted_at Column using Migration:

let's create new migration using following command:

php artisan make:migration add_soft_delete_posts

next, updated migration file as like the below:

database/migrations/2023_01_16_134448_add_soft_delete_posts.php

<?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::table('posts', function(Blueprint $table)

{

$table->softDeletes();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::table('posts', function(Blueprint $table)

{

$table->dropSoftDeletes();

});

}

};

Now, you can run migration:

php artisan migrate

Step 2: Use Soft Delete in Model

we need to use Illuminate\Database\Eloquent\SoftDeletes facade in model and use SoftDeletes class.

let's update Post.php model class.

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 $dates = ['deleted_at'];

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'title', 'body', 'status'

];

}

Step 3: Delete Record

You can remove record as like below query code:

$post = Post::find(1);

$post->delete();

Output:

i hope it can help you...

Tags :