Android Cache Data Clear 2

How to Implement Soft Delete in Laravel?

Some times we do not want to delete something entirely from Database. For example, if a user deletes a photo from database then our website should not show photo to him or in collection of photos but photo should stay in our database and we as admin can see that photo. It is very controversial but very easy to implement in Laravel. Lets implement that.

First we will create migration with this code for photos table.

Schema::create('photos', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('path');
            $table->softDeletes();
            $table->timestamps();
});

SoftDeletes() method will create deleted_at column in photos table. Now we can select all photos by using simple all() method.

$photos = Photo::all();

Now this will give all photos. Now lets say we delete first photo. So easy syntax.

$photo = Photo::first();
$photo->delete();

Now if you will call all() method then this photo is deleted. So you can show this output to client. But you will see that this only added timestamp in deleted_at column in photos table. Now as admin if you want to see deleted photos then you need to run this.

$photos = Photo::onlyTrashed()->get();

I hope now soft delete is very easy to implement for you. If you face any problem let’s know in comments. We will address it.