In this tutorials we will learn how to use soft delete in Laravel 8 When we use soft delete in the project then records are not actually removed from the database. Instead of that timestamp has been assigned to the deleted_at column.

I will guide you step by step how to use soft delete in laravel.so just follow the step to use soft delete in our application.

First add soft delete in our model:

<?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;
    use SoftDeletes;    
    protected $fillable=[
        'title','description','content','image','published_at'
    ];
}

Add following code in migration file

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->text('content');
            $table->string('image');
            $table->timestamp('published_at');
            $table->softDeletes();
            $table->timestamps();
        });
    }

You should also add the deleted_at column to your database table.so what we do is we just add only new column in database.Belove command add only new column to the database

php artisan make:migration add_soft_deletes_to_posts_table --table=posts

It will be create new migration file in database/migration folder.

Add soft delete in new migration file up method:

public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->softDeletes();
        });
    }

And add drop soft delete in migration down method:

public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropSoftDeletes();
        });
    }

Now run php artisan migrate for newly add migrate

Set post controller destroy method

public function destroy(post $post)
    {
        $post->delete();
        session()->flash('success','Post Deleted successfully');
        return redirect(route('posts.index'));
    }

So  in this tutorial  we used soft delete it will not delete record in database but only deleted_at column will be set to the current date and time.

We hope this article helped you to learn soft deleting in Laravel.

Similar Posts

Leave a Reply

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