How to use soft delete in Laravel?

How to use soft delete in Laravel?

In this post we will give you information about How to use soft delete in Laravel?. Hear we will give you detail about How to use soft delete in Laravel?And how to use it also give you demo for it if it is necessary.

Normally, we remove row from database when delete record from site. But laravel 5 introduce SoftDeletes in models that way we can’t remove from database but if remove record from front side then it doesn’t show record on front. So we can retrieve record from database if we remove wrong row.

How work soft delete, laravel add

deleted_at column on the table that be default will be null and when we remove then it will place current timestamp, Laravel Model always fetch that record have only deleted_at = null.

So, how to use in our project, so first when you create table moigration then you have to add softDeletes(). you can see like bellow example of migration.

Migration Example:

use IlluminateDatabaseSchemaBlueprint;

use IlluminateDatabaseMigrationsMigration;


class CreateItemsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('items', function(Blueprint $table) {

$table->increments('id');

$table->string('title');

$table->text('description');

$table->softDeletes();

$table->timestamps();

});

}


/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::drop("items");

}

}


Ok, now you can find deleted_at column in your items table and you have also model should look like as bellow:

Items Model

namespace App;


use IlluminateDatabaseEloquentModel;

use IlluminateDatabaseEloquentSoftDeletes;


class Item extends Model

{

use SoftDeletes;


public $fillable = ['title','description'];


/**

* The attributes that should be mutated to dates.

*

* @var array

*/

protected $dates = ['deleted_at'];


}

Now, you can use Item model as normally like you use before, you get all record like this way.

$data = Item::get();

It will return all record that have deleted_at = null only and you can also remove record like this way:

$data = Item::find(1)->delete();

You can check and use it’s really good….

Hope this code and post will helped you for implement How to use soft delete in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

71  +    =  76

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US