How to Use Soft Delete in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hey Dev,

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, laravel 10 and laravel 11 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:

database/migrations/2023_01_16_134448_create_posts_table.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::create('posts', function(Blueprint $table)

{

$table->id();

$table->string('title');

$table->text('body');

$table->tinyInteger('status')->default(0);

$table->timestamps();

$table->softDeletes();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

};

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.

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 :
Shares