Hello Devs,
In this tutorial, we are going to see example of laravel 7 soft delete.
Follow this step by step guide given below:
Create Post Migration Soft Delete
php artisan make:migration CreatePostsTable
/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
/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
$data = Blog::get();
Delete one Record
$data = Blog::find(1)->delete();
Get All Records After Delete one Record
$data = Blog::withTrashed()->get();
I hope this example helps you.