Laravel 7 Soft Delete Example

10-Apr-2023

.

Admin

Laravel 7 Soft Delete Example

This article will give you example of laravel 7 soft delete. you can understand a concept of soft delete laravel 7 example. step by step explain laravel 7 deleted_at migration. This post will give you simple example of laravel 7 soft delete migration. You just need to some step to done laravel 7 SoftDeletes.

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 7.

Create Post Migration Soft Delete


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

/database/migrations/2020_01_02_095534_create_blogs_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('blogs', 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('blogs');

}

}

Create Post Model Soft Delete

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

/app/Blog.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\SoftDeletes;

class Blog 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 Blog model as normally like you use before, you get all record like this way.

$data = Blog::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 = Blog::find(1)->delete();

Get All Records After Delete one Record

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

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

You can check the table records.

It will help you..

#Laravel 7