Create Recycle Bin In Laravel Using Eloquent Soft Delete

Hello artisan, in this soft delete query in laravel i am going to show you that how to create recycle bin with soft delete in Laravel. Than we will create delete and restore system in laravel using soft delete. This laravel trash box example will give you simple example of how to restore soft deleted data in laravel. 

Look, you have seen that when we delete email, that deleted email is not permanently deleted. It'll inserted into trash box. We are going to create this exact feature in this tutorial using Laravel soft delete. Soft delete gives a deleted_at field. When we delete a row then this field filled with a date_time. If we null that deleted_at field then we will get back out deleted row.

This is a cool feature of Laravel but remember soft delete only works in laravel eloquent. In this example, i will show you step by step how to restore soft delete data in laravel. I will add soft delete in users table, then we will list that users where you can delete that users as well and i will add a restore button to get back that deleted data. So let's start.

 

Step 1: Install Laravel

In the first step of laravel restore soft delete example we need a fresh laravel project. So download it via command line:

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

 

Step 2: Add SoftDelete in User Model

Here in this tutorial i am going to use existing laravel users table. So i need add soft delete in user model and table. So we have to laravel add soft delete to existing table and 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

 

Update migration file like that

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();
        });
    }
}

 

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

app/Models/User.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 Some Users

In this step, we need to create some dummy users using factory to check our Laravel trash box with soft delete.

php artisan tinker

//then

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

 

Step 4: Add Route

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

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
  
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: Add Controller

Now we almost set to go to create this laravel delete and restore data using soft delete via withTrashed method. In this fifth step, we need to create UserController and add following code on that file:

app/Http/Controllers/UserController.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(10);
          
        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

All are set to go. Now we have to create blade file to view our user list with trash box. So let's create view file to see that:

resources/views/users.blade.php

 

Read also: Laravel 8.x Soft Delete Example Tutorial

 

Hope it can help you.

 

#laravel #laravel-8x #soft-delete