Monday, 5 July 2021

How to use Soft Delete to Restore Deleted Data in Laravel


In this Laravel tutorial we are going to learn How to use Soft Delete in Laravel framework. We will seen how can we restore deleted records and again we can see that records in our Laravel application with the help of soft delete.

So when we have use Soft Delete in our Laravel application so when we have delete data from our web application then that data is not deleted from database but that data we cannot see at our web application front-end side and at back-end side we can again recover and display or list in our application. So this things we will discuss under this tutorial by taking practical example how soft delete work in Laravel crud application.

How to Work Laravel Soft Delete


Suppose we have use Soft delete in Laravel web application, so when we have remove data from our application then that data is not actually removed from Mysql Database table. But current timestamp time has been updated at the deleted_at column. And when we have restore that deleted data then current timestamp value will be updated with nulled in deleted_at table column.

Please follow below step for how to implement soft delete in Laravel application for restore deleted records.


Preview


How to use Soft Delete to Restore Deleted Data in Laravel

Install Laravel Framework


For implement SoftDelete, first we need to download fresh copy of Laravel framework. So we have to go to command prompt and run following command.


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


This command will first make soft_delete directory and under that directory it will download fresh copy of Laravel framework.




Make Database Connection


After download latest version of Laravel framework, first we need to make databae connection. So for make database connection in Laravel application, we have to open .env file and under that file we have to define our MySQL database configuration details.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Create Model Class


Once you have make database connection in Laravel framework, then in next step we have to create one model class and migration file for create table in MySQL database. So for this, we have to run following command in command prompt.


php artisan make:model Post -m


This command will make Post.php models class file in app/Models directory and migration file under database/migrations folder. First we have open migrations directory file and under that file, we have to define table column details which you can seen below.

database/migrations/2021_07_05_065844_create_posts_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('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
    }

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



After this, we have to run following command in command prompt.


php artisan migrate

This command will run migration process and it will create posts table in your mysql database with following table column.


How to use Soft Delete to Restore Deleted Data in Laravel

Add SoftDelete in Models Class


Now in this steps we have to add Soft Delete in our Post.phpmodels class. But before we need create migrations for adding soft delete to posts table. So for this we have to run following command in command prompt.


php artisan make:migration add_sorft_delete_column


This above command will create new migration file at database/migrations directory which you can seen below.

database/migrations/new_migration_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('posts', function(Blueprint $table){
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function(Blueprint $table){
            $table->dropSoftDeletes();
        });
    }
}



After this we have to run migration command in command prompt.


php artisan migrate


Once you have run this command, then it will add deleted_at table column to posts table which you can seen below.


How to use Soft Delete to Restore Deleted Data in Laravel


Now for add dummy data, you have to run following sql script, so it will insert some dummy data in posts table.


INSERT INTO `posts` (`id`, `title`, `description`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Ajax Pagination using PHP with JavaScript', 'Ajax Pagination using PHP with JavaScript', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(2, 'Ajax Live Data Search using JavaScript with PHP', 'Ajax Live Data Search using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(3, 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', '2021-07-02 07:27:03', '2021-07-03 06:35:02', NULL),
(4, 'How to Create Review & Rating Page in PHP with Ajax', 'How to Create Review & Rating Page in PHP with Ajax', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(5, 'Submit Form without Page Refresh using JavaScript with PHP', 'Submit Form without Page Refresh using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(6, 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(7, 'How to Export Data in Excel using Codeigniter 4', 'How to Export Data in Excel using Codeigniter 4', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(8, 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(9, 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(10, 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4	', 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4', '2021-07-02 07:27:04', '2021-07-02 07:27:04', NULL);


Next we want to add soft delete facade in our Post model, you can below find source code for add SoftDelete facade in Post models class.

app/Models/Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['title', 'description'];

    protected $dates = ['deleted_at'];
}





Create Controller Class


In next step, we have to create PostController and add following code in that controller file. So for create controller class file, we have need to run following command in command prompt.


php artisan make:controller PostController


This command will create PostController.php file at app/Http/Controllers directory. So need to open that file and add following code.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::get();

        if($request->has('view_deleted'))
        {
            $posts = Post::onlyTrashed()->get();
        }

        return view('post', compact('posts'));
    }

    public function delete($id)
    {
        Post::find($id)->delete();

        return back()->with('success', 'Post Deleted successfully');
    }

    public function restore($id)
    {
        Post::withTrashed()->find($id)->restore();

        return back()->with('success', 'Post Restore successfully');
    }

    public function restore_all()
    {
        Post::onlyTrashed()->restore();

        return back()->with('success', 'All Post Restored successfully');
    }
}



Under this controller class file we have make following method.

index(Request $request) : This method will fetch data on condition, suppose there is view_deleted variable has been received in url then it has only fetch deleted data otherwise it has fetch all data from database and send to view blade file.

delete($id) : This method has received request for delete data and it has received id in request, so based on value of that id it will perform soft delete operation.

restore($id) : This method has received get request for restore single data, so with restore request it has received id and that id data has been restore.

restore_all() : This method has received get request for restore all deleted data.

Create View Blade File


In Laravel framework for display output on browser we need to create blades file for display data on web page. In this example we have create blade file resources/views/post.blade.php directory.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Use Soft Delete in Laravel</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">How to Use Soft Delete in Laravel</h1>
            <br />
            @if(session()->has('success'))

                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>

            @endif
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-md-6">Sample Data</div>
                        <div class="col col-md-6 text-right">
                            @if(request()->has('view_deleted'))

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

                            <a href="{{ route('post.restore_all') }}" class="btn btn-success btn-sm">Restore All</a>

                            @else

                            <a href="{{ route('post.index', ['view_deleted' => 'DeletedRecords']) }}" class="btn btn-primary btn-sm">View Deleted Post</a>

                            @endif
                            
                        </div>
                    </div>
                </div>
            
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            @if(count($posts) > 0)
                                @foreach($posts as $row)

                                <tr>
                                    <td>{{ $row->id }}</td>
                                    <td>{{ $row->title }}</td>
                                    <td>{{ $row->description }}</td>
                                    <td>
                                        @if(request()->has('view_deleted'))

                                            <a href="{{ route('post.restore', $row->id) }}" class="btn btn-success btn-sm">Restore</a>
                                        @else
                                            <form method="post" action="{{ route('post.delete', $row->id) }}">
                                                @csrf
                                                <input type="hidden" name="_method" value="DELETE" />
                                                <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                            </form>
                                        @endif
                                    </td>
                                </tr>

                                @endforeach
                            @else
                                <tr>
                                    <td colspan="4" class="text-center">No Post Found</td>
                                </tr>

                            @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>


Set Route


Under this step we need to set route for PostController.php class method. So for set file we need to open routes/web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

Route::get('/', function () {
    return view('welcome');
});


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

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

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

Route::get('post/restore_all', [PostController::class, 'restore_all'])->name('post.restore_all');


Run Laravel Application


After follow all above step now we want to check Laravel application output. So first we have run server. So for this we have to run following command in command prompt.


php artisan serve

This command will star server and provide us base url of our Laravel application. So for check output of above code, we have to hit following url in browser.


http://127.0.0.1:8000/post


So this are the complete process for how to use SoftDelete in Laravel and implement Restore Deleted Records feature in your Laravel application. We hope this tutorial will help you to learn something new in Laravel framework.

Download Complete Source Code


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.





3 comments:

  1. sandeepsingh@pau.edu

    ReplyDelete
  2. Please send me on this address
    sandeepsingh@pau.edu

    ReplyDelete
  3. Sandeepsinghkhalsa.0013@gmail.com

    ReplyDelete