How to Use Soft Delete in Laravel?
Are you looking for an example of how to use soft delete in laravel. It's a simple example of how to apply soft delete in laravel. This post will give you a simple example of how to soft delete in laravel 9. step by step explain laravel soft delete migration. So, let us dive into the details.
Soft deleting in Laravel allows you to mark a database record as "deleted" instead of actually deleting it from the database. This means that the record is still stored in the database, but it is ignored by default when retrieving data using the model. Soft deleting can be useful when you want to retain a record's history or when you want to be able to restore a deleted record.
In this example, we will create posts table and we will add soft delete on it. we need to do following two things to apply soft delete in laravelL:
1. Create Migration and add deleted_at column using softDeletes() function.
2. Use Illuminate\Database\Eloquent\SoftDeletes facade in model and use SoftDeletes class.
You can also use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 version.
So, let's see the following step to adding soft delete in laravel model.
Step 1: Create Migration with softDeletes()
let's create new migration using following command:
php artisan make:migration create_posts_table
next, updated migration file as like the below:
return new class extends Migration
* Run the migrations.
* @return void
public function up()
Schema::create('posts', function(Blueprint $table)
* Reverse the migrations.
* @return void
public function down()
Now, you can run migration:
php artisan migrate
Step 2: Create Model with SoftDeletes
we need to use Illuminate\Database\Eloquent\SoftDeletes facade in model and use SoftDeletes class.
let's update Post.php model class.
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);
i hope it can help you...
We are Recommending you
- Laravel Migration Default Value Current Timestamp Example
- How to Run Migration and Seeder on Laravel Vapor?
- How to Change Column Length using Laravel Migration?
- How to Update Enum Value in Laravel Migration?
- Laravel Migration Add Enum Column Example
- Laravel Unique Validation With Soft Delete Example
- Laravel Migration - How to Add New Column in Existing Table ?
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- How to Change Column Name and Data Type in Laravel Migration?
- How to Create Table using Migration in Laravel?
- How to Get Soft Deleted Records in Laravel?
- How to Use Soft Delete in Laravel?