How to Restore Deleted Records in Laravel?

By Hardik Savani June 26, 2021 Category : Laravel

Hi Dev,

Here, i will show you laravel restore deleted records. This article will give you simple example of laravel get soft deleted records. This post will give you simple example of how to restore soft deleted data in laravel. if you have question about how to restore deleted records in laravel then i will give simple example with solution.

In this example, i will show you step by step how to restore soft deleted data in laravel. we will add soft delete in users table, then we will list that users where you can delete that users as well. we will also add one more button where you can view all deleted records. we will also add restore and restore all buttons where you can restore deleted items.

so let's follow bellow step and get done like as bellow screenshot. you can also use this example with laravel 6, laravel 7 and laravel 8 version.

Preview:

Step 1: Install Laravel

first of all we need to get fresh Laravel 8 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Add SoftDelete in User Model

here, we will create migration for adding softdelete to users table. so let's create migration as bellow:

php artisan make:migration add_sorft_delete_column

database/migrations/your_migtion_file.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class AddSorftDeleteColumn extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::table('users', function(Blueprint $table){

$table->softDeletes();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::table('users', function (Blueprint $table) {

$table->dropSoftDeletes();

});

}

}

now let's run migration:

php artisan migrate

next, add soft delete facade in user model as like bellow:

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable

{

use HasFactory, Notifiable, SoftDeletes;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password'

];

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

/**

* The attributes that should be cast to native types.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

}

Step 3: Add Dummy Users

In this step, we need to create add some dummy users using factory.

php artisan tinker

User::factory()->count(10)->create()

Step 4: Create Route

In this is step we need to create some routes for add to cart function.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('users', [UserController::class, 'index'])->name('users.index');

Route::delete('users/{id}', [UserController::class, 'delete'])->name('users.delete');

Route::get('users/restore/one/{id}', [UserController::class, 'restore'])->name('users.restore');

Step 5: Create Controller

in this step, we need to create UserController and add following code on that file:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$users = User::select("*");

if ($request->has('view_deleted')) {

$users = $users->onlyTrashed();

}

$users = $users->paginate(8);

return view('users', compact('users'));

}

/**

* Write code on Method

*

* @return response()

*/

public function delete($id)

{

User::find($id)->delete();

return back();

}

/**

* Write code on Method

*

* @return response()

*/

public function restore($id)

{

User::withTrashed()->find($id)->restore();

return back();

}

/**

* Write code on Method

*

* @return response()

*/

public function restoreAll()

{

User::onlyTrashed()->restore();

return back();

}

}

Step 6: Create Blade Files

here, we need to create blade files for users, products and cart page. so let's create one by one files:

resources/views/users.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Restore Deleted Records in Laravel? - ItSolutionStuff.com</title>

<meta name="csrf-token" content="{{ csrf_token() }}">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>

<body>

<div class="container">

<h1>How to Restore Deleted Records in Laravel? - ItSolutionStuff.com</h1>

@if(request()->has('view_deleted'))

<a href="{{ route('users.index') }}" class="btn btn-info">View All Users</a>

<a href="{{ route('users.restore.all') }}" class="btn btn-success">Restore All</a>

@else

<a href="{{ route('users.index', ['view_deleted' => 'DeletedRecords']) }}" class="btn btn-primary">View Delete Records</a>

@endif

<table class="table table-bordered data-table">

<thead>

<tr>

<th>No</th>

<th>Name</th>

<th>Email</th>

<th>Action</th>

</tr>

</thead>

<tbody>

@foreach($users as $user)

<tr>

<td>{{ $user->id }}</td>

<td>{{ $user->name }}</td>

<td>{{ $user->email }}</td>

<td>

@if(request()->has('view_deleted'))

<a href="{{ route('users.restore', $user->id) }}" class="btn btn-success">Restore</a>

@else

<form method="POST" action="{{ route('users.delete', $user->id) }}">

@csrf

<input name="_method" type="hidden" value="DELETE">

<button type="submit" class="btn btn-xs btn-danger btn-flat show_confirm" data-toggle="tooltip" title='Delete'>Delete</button>

</form>

@endif

</td>

</tr>

@endforeach

</tbody>

</table>

</div>

</body>

<script type="text/javascript">

$('.show_confirm').click(function(e) {

if(!confirm('Are you sure you want to delete this?')) {

e.preventDefault();

}

});

</script>

</html>

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/users

i hope it can help you...

Tags :