Monday, June 20, 2016

How to use Soft Delete in your Laravel Application?


laravel soft delete



By hearing the term Soft Delete first question in your mind is What is Soft Delete. So Before starting the session, I'm gonna give you a basic idea about Soft Delete First.

What is Soft Delete?

     - Basically it's a process of deleting data which will be displayed in frond end but without deleting the actual data from database. So in simple word, data will deleted from your application but it'll be there in your database. It actually used for keep tracking the data by whom data get deleted or when. So in this situation we used Soft Delete.

How do I implement Soft Delete in my application? 


Then Let's start the discussion, how you can use soft delete.

1. In your migration file add the following line after  $table->timestamps(); in your Schema :
$table->softDeletes();

Or, if you want to put manually in your database, add a datetime() field named 'deleted_at' in your table and it should be nullable.

2. Here I'm giving a demo Model where the given field is required for using Soft Delete in your Model.

Demo Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class YourModel extends Model
{
 use SoftDeletes; 
    protected $table="table_name";
    


protected $dates = ['deleted_at']; 
    protected $fillable=[];
}

3. There's no need to change controller code, means you don't need to change or add any code for using soft delete in your controller. Normal delete() method you can use for deleting the data.

So that's it about Soft Delete. You can use it in your application and you can keep track of data anytime though it's get deleted.

Stay connected with my blog. Because New topic will be covered soon. Thank you.




Related Articles

0 comments:

Post a Comment