article

Saturday, March 18, 2023

Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete

Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel>composer create-project --prefer-dist laravel/laravel my-app

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Controller UserController
php artisan make:controller UserController
C:\xampp\htdocs\laravel\my-app>php artisan make:controller UserController
app\Http\Controllers\UserController.php

//app\Http\Controllers\UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index(){
        $users=User::all();
        return view('user',compact('users'));
    }

    public function softDelete($id){
        User::find($id)->delete();
        return back();
    }

    public function trashed(){
        $users = User::onlyTrashed()->get();
        return view('trashed',compact('users'));
    }

    public function restore($id){
        User::whereId($id)->restore();
        return back();
    }

    public function restoreAll(){
        User::onlyTrashed()->restore();
        return back();
    }

    public function forceDelete($id){
        User::find($id)->forceDelete();
        return back();
    }
}
Database Migration
database/migrations/create_users_table.php
//database/migrations/create_users_table.php
<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->timestamp('deleted_at')->nullable(); //add deleted_at
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
};
run this migration
C:\xampp\htdocs\laravel\my-app>php artisan migrate

php artisan tinker

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

C:\xampp\htdocs\laravel9\blog>php artisan tinker
Psy Shell v0.11.1 (PHP 8.0.13 — cli) by Justin Hileman
>>> User::factory()->count(20)->create()
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.

check database table user 100 dummy records added

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

resources/views/user.blade.php
//resources/views/user.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
</head>
<body>
    <div class="container">
        <h1 class="text-center text-success pt-4">Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete</h1>
        <hr>
    <div class="row py-2">
        <div class="col-md-6">
            <h2>List of Users</h3>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <b><a class="btn btn-default m-2" href="/"><i class="fa fa-thin fa-newspaper"></i> List of Users</a>
                <a class="btn btn-default m-2" href="trashed"> <i class="fa fa-duotone fa-trash"></i>   Trashed</a></b>
            </div>
        </div>
    </div>
    <table id="example" class="table  table-bordered table-hover display">
        <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Name</th>
                <th scope="col">Email</th>
                <th scope="col">Soft Delete</th>
                <th scope="col">Force Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($users as $rs)
                <tr>
                    <th scope="row">{{$rs->id}}</th>
                    <td>{{$rs->name}}</td>
                    <td>{{$rs->email}}</td>
                <td ><a href="softDelete/{{$rs->id}}" class="text-warning btn"><i class="fa fa-solid fa-trash"></i> Delete</a></td>
                <td ><a href="forceDelete/{{$rs->id}}" class="text-danger btn"><i class="fa fa-solid fa-trash"></i> Forever</a></td>
                </tr>
            @endforeach
        </tbody>
    </table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
 $(document).ready(function () {
    $('#example').DataTable();
});
</script>
</body>
</html>
resources/views/trashed.blade.php
//resources/views/trashed.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
</head>
<body>
    <div class="container">
        <h1 class="text-center text-success pt-4">Laravel Soft Deletes - Restore Records, Force Delete, Fetch Deleted Records and Soft Delete</h1>
        <hr>
    <div class="row py-2">
        <div class="col-md-6">
            <h2>Restore Deleted Users</h3>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <b><a class="btn btn-default m-2" href="/"><i class="fa fa-thin fa-newspaper"></i> List of Users</a>
                <a class="btn btn-default m-2" href="trashed"> <i class="fa fa-duotone fa-trash"></i>   Trashed</a></b>
            </div>
        </div>
    </div>
    <h3><a class="btn btn-success" href="/restore-all"><i class="fa fa-sharp fa-solid fa-trash-arrow-up"></i> Restore All</a></h3>
    <table id="example" class="table  table-bordered table-hover display">
        <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">Name</th>
                <th scope="col">Email</th>
                <th scope="col">Restore</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($users as $rs)
                <tr>
                    <th scope="row">{{$rs->id}}</th>
                    <td>{{$rs->name}}</td>
                    <td>{{$rs->email}}</td>
                    <td><a href="restore/{{$rs->id}}" class="text-primary btn"><i class="fa fa-sharp fa-solid fa-trash-arrow-up"></i></a></td>
                </tr>
            @endforeach       
        </tbody>
    </table>
    </div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
 $(document).ready(function () {
    $('#example').DataTable();
});
</script>
</body>
</html>
Model User
app/models/User.php

//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 Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes; //add SoftDeletes

    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Routes
routes/web.php
//routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

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

Route::get('/',[UserController::class,'index']);
Route::get('/softDelete/{id}',[UserController::class,'softDelete']);
Route::get('forceDelete/{id}',[UserController::class,'forceDelete']);

Route::get('trashed',[UserController::class,'trashed']);
Route::get('restore/{id}',[UserController::class,'restore']);
Route::get('restore-all',[UserController::class,'restoreAll']);
Run C:\xampp\htdocs\laravel\my-app>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post