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 IlluminateDatabaseEloquentSoftDeletes 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 IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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 IlluminateDatabaseEloquentSoftDeletes facade in model and use SoftDeletes class.
let’s update Post.php model class.
app/Models/Post.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
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…