Restore deleted record in Laravel

Restore back deleted record in Laravel

In this tutorial, I will give you an example of Restore back deleted record in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application, Sometimes we need to use restore back or undo deleted records from Database using Undo or Restore Button in Blade file according to project or client requirement in Laravel application.

Concept of restore back deleted records in Laravel

Sometimes Our Important Data deleted accidentally when we do not use not using any alert or warning message.

In this case, you will need to be contacted by a developer or database administrator to Restored back your deleted Data.

Laravel Eloquent ORM provides us soft delete trait, we use this trait with trashed to restore or recover data, I will give you a quick tip to undo or restore data in Laravel Project.

Generating Migration :

php artisan make:migration undo_data_restore_examples_table

Migration Structures :

database\migrations

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUndoDataRestoreExamples extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('undo_data_restore_examples', function (Blueprint $table) {
            $table->id();
            $table->string('name',25);
            $table->string('address',70);
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('undo_data_restore_examples');
    }
}

Run Migration :

php artisan:migrate
Restore back deleted record in Laravel

Make Model :

app\Model\UndoDataRestore

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class UndoDataRestore extends Model
{
    use SoftDeletes;
    protected $table = 'undo_data_restore_examples';
}

Generate Dummy Data Using Seeder-Faker :

Now we insert some dummy records in our undo_data _restore examples table, using Faker.

database\seeds\DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
    	$faker = Faker::create();
    	foreach(range(1,10) as $index)
    	{
    		DB::table('undo_data_restore_examples')->insert([
    			'name' => $faker->text(10),
    			'address'  => $faker->text(40),
    		]);
    	}
        // $this->call(UsersTableSeeder::class);
    }
}

Run Seeder :

php artisan db:seed

After successfully running the seed command in a terminal, we have 10 records in our undo_data_restore_examples table in the Database.

Restore back deleted record in Laravel

routes/web.php :

#Undo Delete Restore Data Routes
Route::get('/data','DataRestoreController@index')->name('data.list');
Route::get('/data-delete/{id}','DataRestoreController@deleteData')->name('data.delete');
Route::get('/data-restore/{id}','DataRestoreController@restore')->name('data.restore');

Controllers\DataRestoreController.php

<?php

namespace App\Http\Controllers;
use App\Model\UndoDataRestore;
use Session;
use Illuminate\Http\Request;

class DataRestoreController extends Controller
{
    public function index(){
        $Getdata = UndoDataRestore::get();
        return view('dataRestore.index',compact('Getdata'));
    }

    public function deleteData($id){
        $deleteData = UndoDataRestore::find($id);
        $deleteData->delete();
        return redirect()->route('data.list')->with('message','Data successfully deleted. <a href="'.route('data.restore',$deleteData->id).'">Whoops, Undo</a>');
    }

    public function restore($id)
    {
    $restoreDataId = UndoDataRestore::withTrashed()->find($id);
    if($restoreDataId && $restoreDataId->trashed()){
       $restoreDataId->restore();
    }
    return redirect()->route('data.list')->with('message','Data restored successfully');
   }
}


In this session variable, we will pass Id in route with flash messages from the controller, and we will call this session in Blade File.

We have a restore function where we get the Id sent by the route, and we check the Id is trashed or not, if the Id is trashed or deleted we restore the Id by clicking on Undo Url.

resources\views\dataRestore\index.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>List Data</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
          <br>
         <h3>Data Restore | Undo Example like Gmail | Laravel | 8Bityard.com</h3>
         <br>
         <div class="row justify-content-end mb-1">
            <div class="col-sm-8">
               @if(Session::has('message'))
               <div class="alert alert-success alert-dismissible p-2">
                  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                  <strong>Success!</strong> {!! session('message')!!}.
               </div>
               @endif
            </div>
         </div>
         <table class="table table-bordered table-sm">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Name</th>
                  <th>Address</th>
                 <th>Action</th>
               </tr>
            </thead>
            <tbody>
                @if ($Getdata->count() > 0 )
               @foreach($Getdata as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{$data->name}}</td>
                  <td>{{$data->address}}</td>
                  <td>
                <a href="{{route('data.delete',$data->id)}}" class="btn btn-danger btn-sm" role="button">Delete</a>
                 </td>
               </tr>
            </tbody>
            @endforeach
            @else
            <h2>No Data Found !</h2>
            @endif
         </table>
      </div>
   </body>
</html>

Run application :

http://127.0.0.1:8000/data
Restore back deleted record in Laravel

You can see we have 10 records in our blade file.


Restore back deleted record in Laravel

Now we delete Id 4 row data.


Restore back deleted record in Laravel

Now you can see we deleted Id row 4 data Successfully, Just click on Undo link.


Restore back deleted record in Laravel

You can see you successfully restored your Id Row 4 Deleted Data within Seconds.


In this article, we learned “How to Restore back deleted record in Laravel”, I hope this article will help you with your Laravel application Project.

Also Read : Infinite scroll pagination in Laravel.