First of all, What is soft Deletes?
Soft deletes create a safeguard system through which data can be recovered without backups, which is very necessary in preventing unintended data loss.
Now that we understand why we need them, let's learn how to implement them!
In your respective Model add the Illuminate\Database\Eloquent\SoftDeletes
Trait:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Test extends Model
{
use HasFactory,SoftDeletes;
}
Now, Add deleted_at
column to the respective table's migration file :
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::table('tests', function (Blueprint $table) { /*Rest of the columns*/ $table->softDeletes(); }); } };
That's it!!
Whenever we run
$test->delete()
, it will add the timestamp of when the delete operation was attempted instead of actually deleting the record./*In Controller*/ public function destroy($id) { Test::findOrFail($id)->delete(); return redirect('viewtests'); }
Let's try and delete first record for First and Fourth Record :
Before:
-
After:
1.)When we fetch data:
2.)In the database:
Now we know how to implement soft delete. Let's take a look into how we can make use of it!!
Before that let's fetch all the data(Including deleted data):
/*In Controller*/
public function display()
{
return view('displayTest', [
//withTrashed Method fetches those records that has been deleted!!
"data" => Test::withTrashed()->orderBy('id', 'asc')->get(),
]);
}
Now our view page will look something like:
Now we'll learn How to restore the deleted data:
/*In Controller*/
public function revive($id)
{
Test::where('id', $id)->restore();
return redirect('/viewtests');
}
That's All !