Complete Laravel 8 Soft Delete & Restore Deleted Records Tutorial
Tags: laravel, mysql, database, tutorial
Published: 2022-04-22 07:02:24

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial

In this post, I will share with you a complete **Laravel 8 soft delete and restore deleted records** tutorial. When developing CRUD operations in Laravel sometimes we need to implement soft deletes. So that if we incorrectly deleted the specific record we can easily restore them. That's why this is important and must exist in our Laravel application.


![complete-laravel-8-soft-delete-restore](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/complete-laravel-8-soft-delete-restore-deleted-records-tutorial-2QZdHNimpWx980.webp?ctm=1636808346)

In this article, You will learn a complete implement with Laravel soft delete and how to restore the deleted records with example.

 

## Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:

```php
composer create-project --prefer-dist laravel/laravel laravel-soft-delete
```

Once done above we need to install the **Laravel Collective Package,** run the following command below:

```php
composer require laravelcollective/html
```

## Step 2: Database Configuration
If your **Laravel project** is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.

 

`.env
`

```php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here
```

## Step 3: Migration Setup
Let's create a migration for our **laravel soft delete **example project. In this example, we are using the user's table which the migration is already exists in Laravel installation. So we just need to edit that migration. See below update code:

```php
<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('email')->unique();
            $table->string('username')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->softDeletes();
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

As you can see we added the **$table->softDeletes();** method to implement the laravel soft delete.

 

Now let's run the following command below:

```php
php artisan migrate
```

## Step 4: Setting up Routes

In my example, I will create manually my crud routes. Just open the **"routes/web.php"** file and add the following routes.

```php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| 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::group(['namespace' => 'App\Http\Controllers'], function()
{   
    /**
     * Home Routes
     */
    Route::get('/', 'HomeController@index')->name('home.index');

    Route::group(['prefix' => 'users'], function() {
        Route::get('/', 'UsersController@index')->name('users.index');
        Route::get('/create', 'UsersController@create')->name('users.create');
        Route::post('/create', 'UsersController@store')->name('users.store');
        Route::get('/{user}/show', 'UsersController@show')->name('users.show');
        Route::get('/{user}/edit', 'UsersController@edit')->name('users.edit');
        Route::patch('/{user}/update', 'UsersController@update')->name('users.update');
        Route::delete('/{user}/delete', 'UsersController@destroy')->name('users.destroy');
        Route::post('/{user}/restore', 'UsersController@restore')->name('users.restore');
        Route::delete('/{user}/force-delete', 'UsersController@forceDelete')->name('users.force-delete');
        Route::post('/restore-all', 'UsersController@restoreAll')->name('users.restore-all');
    });
});
```

As you can see we added restore, force-delete, and restore-all routes. You will see our controller code for these routes.

 

## Step 5: Setting up Model for our Soft delete

As you can see below we imported the use Illuminate\Database\Eloquent\SoftDeletes; class and use it in our User model.

```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;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'username',
        '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',
    ];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * Always encrypt password when it is updated.
     *
     * @param $value
     * @return string
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}
```

## Step 6: Laravel Soft Delete & Restore Deleted Records Controller Methods
 

Index method inside UserController.php as you can see I checked if there is a status with the archived value from the request and call the method **$users->onlyTrashed()** so that only soft deleted will be shown on the lists.

```php
/**
 * Display all users
 * 
 * @return \Illuminate\Http\Response
 */
public function index(Request $request) 
{
    $users = User::latest();

    if($request->get('status') == 'archived') {
        $users = $users->onlyTrashed();
    }

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

    return view('users.index', compact('users'));
}
```
In this method inside UserController.php I called the **withTrashed()** and **restore()** methods this will allow us to restore the deleted record.


```php
/**
 *  Restore user data
 * 
 * @param User $user
 * 
 * @return \Illuminate\Http\Response
 */
public function restore($id) 
{
    User::where('id', $id)->withTrashed()->restore();

    return redirect()->route('users.index', ['status' => 'archived'])
        ->withSuccess(__('User restored successfully.'));
}

```

This is the implementation of forced to delete the trashed record using **forceDelete()** method.

```php
/**
 * Force delete user data
 * 
 * @param User $user
 * 
 * @return \Illuminate\Http\Response
 */
public function forceDelete($id) 
{
    User::where('id', $id)->withTrashed()->forceDelete();

    return redirect()->route('users.index', ['status' => 'archived'])
        ->withSuccess(__('User force deleted successfully.'));
}
```

In this action, we called the **onlyTrashed()** and **restore()** methods so that we will all restore the records that are trashed.

```php
/**
 * Restore all archived users
 * 
 * @param User $user
 * 
 * @return \Illuminate\Http\Response
 */
public function restoreAll() 
{
    User::onlyTrashed()->restore();

    return redirect()->route('users.index')->withSuccess(__('All users restored successfully.'));
}
```

## Step 7: Laravel Soft Delete User Controller

Below are the complete code for our UserController.php with implementations of Laravel 8 soft delete and restore deleted records.

```php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;

class UsersController extends Controller
{
    /**
     * Display all users
     * 
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) 
    {
        $users = User::latest();

        if($request->get('status') == 'archived') {
            $users = $users->onlyTrashed();
        }

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

        return view('users.index', compact('users'));
    }

    /**
     * Show form for creating user
     * 
     * @return \Illuminate\Http\Response
     */
    public function create() 
    {
        return view('users.create');
    }

    /**
     * Store a newly created user
     * 
     * @param User $user
     * @param StoreUserRequest $request
     * 
     * @return \Illuminate\Http\Response
     */
    public function store(User $user, StoreUserRequest $request) 
    {
        //For demo purposes only. When creating user or inviting a user
        // you should create a generated random password and email it to the user
        $user->create(array_merge($request->validated(), [
            'password' => 'test' 
        ]));

        return redirect()->route('users.index')
            ->withSuccess(__('User created successfully.'));
    }

    /**
     * Show user data
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function show(User $user) 
    {
        return view('users.show', [
            'user' => $user
        ]);
    }

    /**
     * Edit user data
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user) 
    {
        return view('users.edit', [
            'user' => $user
        ]);
    }

    /**
     * Update user data
     * 
     * @param User $user
     * @param UpdateUserRequest $request
     * 
     * @return \Illuminate\Http\Response
     */
    public function update(User $user, UpdateUserRequest $request) 
    {
        $user->update($request->validated());

        return redirect()->route('users.index')
            ->withSuccess(__('User updated successfully.'));
    }

    /**
     * Delete user data
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user) 
    {
        $user->delete();

        return redirect()->route('users.index')
            ->withSuccess(__('User deleted successfully.'));
    }

    /**
     *  Restore user data
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function restore($id) 
    {
        User::where('id', $id)->withTrashed()->restore();

        return redirect()->route('users.index', ['status' => 'archived'])
            ->withSuccess(__('User restored successfully.'));
    }

    /**
     * Force delete user data
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function forceDelete($id) 
    {
        User::where('id', $id)->withTrashed()->forceDelete();

        return redirect()->route('users.index', ['status' => 'archived'])
            ->withSuccess(__('User force deleted successfully.'));
    }

    /**
     * Restore all archived users
     * 
     * @param User $user
     * 
     * @return \Illuminate\Http\Response
     */
    public function restoreAll() 
    {
        User::onlyTrashed()->restore();

        return redirect()->route('users.index')->withSuccess(__('All users restored successfully.'));
    }
}
```

## Step 8: Index Blade View
Code below about our index.blade.php which we code the Laravel soft delete implementations.

```php
@extends('layouts.app-master')

@section('content')
    
    <h1 class="mb-3">Laravel Soft Delete Example - codeanddeploy.com</h1>

    <div class="bg-light p-4 rounded">
        <h1>Users</h1>
        <div class="lead">
            Manage your users here.
            <a href="{{ route('users.create') }}" class="btn btn-primary btn-sm float-right">Add new user</a>
        </div>
        
        <div class="mt-2">
            @include('layouts.partials.messages')

            <br>
            <a href="/users">All users</a> | <a href="/users?status=archived">Archived users</a>

            <br><br>
            @if(request()->get('status') == 'archived')
                {!! Form::open(['method' => 'POST','route' => ['users.restore-all'],'style'=>'display:inline']) !!}
                {!! Form::submit('Restore All', ['class' => 'btn btn-primary btn-sm']) !!}
                {!! Form::close() !!}
            @endif
        </div>

        <table class="table table-striped">
            <thead>
            <tr>
                <th scope="col" width="1%">#</th>
                <th scope="col" width="15%">Name</th>
                <th scope="col">Email</th>
                <th scope="col" width="10%">Username</th>
                <th scope="col" width="1%" colspan="4"></th>    
            </tr>
            </thead>
            <tbody>
                @foreach($users as $user)
                    <tr>
                        <th scope="row">{{ $user->id }}</th>
                        <td>{{ $user->name }}</td>
                        <td>{{ $user->email }}</td>
                        <td>{{ $user->username }}</td>
                        <td><a href="{{ route('users.show', $user->id) }}" class="btn btn-warning btn-sm">Show</a></td>
                        <td><a href="{{ route('users.edit', $user->id) }}" class="btn btn-info btn-sm">Edit</a></td>
                        <td>
                            @if(request()->get('status') == 'archived')
                                {!! Form::open(['method' => 'POST','route' => ['users.restore', $user->id],'style'=>'display:inline']) !!}
                                {!! Form::submit('Restore', ['class' => 'btn btn-primary btn-sm']) !!}
                                {!! Form::close() !!}
                            @else
                                {!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
                                {!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
                                {!! Form::close() !!}
                            @endif
                        </td>
                        <td>
                            @if(request()->get('status') == 'archived')
                                {!! Form::open(['method' => 'DELETE','route' => ['users.force-delete', $user->id],'style'=>'display:inline']) !!}
                                {!! Form::submit('Force Delete', ['class' => 'btn btn-danger btn-sm']) !!}
                                {!! Form::close() !!}
                            @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>

        <div class="d-flex">
            {!! $users->links() !!}
        </div>

    </div>
@endsection
```

Now you have the complete implementations for Laravel soft delete including restoring deleted records. 

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/complete-laravel-8-soft-delete-restore-deleted-records-tutorial if you want to download this code.

Happy coding :)