Laravel 7/6 Soft Delete Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

18666

03-01-2020


Laravel 7/6 Soft Delete Example

Hi Guys,

In this tutorial , i will exmaple how to use soft delete in laravel 7/6,we are tell simple example of laravel 7/6 soft delete.it will laravel 7/6 soft delete migration.

we remove row from database when delete record from site. But laravel 6 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.

Here i bellow example you can learn soft delete in laravel 6

Create Post Migration Soft Delete


In this post migration open Post migration file and put the below same code.

Path: /database/migrations/2020_01_02_095534_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

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

$table->bigIncrements('id');

$table->string('title');

$table->text('body');

$table->softDeletes();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('posts');

}

}

Create Post Model Soft Delete

Next, go to app/Post.php and open post model file and put the below same code.

now you can find deleted_at column in your post table and you have also model should look like as bellow

here following path of model fille

Path:/app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model

{

use SoftDeletes;

protected $fillable = ['title','body'];

/**

* The attributes that should be mutated to dates.

*

* @var array

*/

protected $dates = ['deleted_at'];

}

Get All Records

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

$data = Post::get();

Delete one Record

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

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

Get All Records After Delete one Record

Now, you can use Post model as normally like you use before, you get all record After Delete one Record like this way.

$data = Post::withTrashed()->get();

You can check the table records.

It will help you..


Recommended Posts