Spread the love

In this article we will learn to restore soft deleted records in Laravel. In our recent article How to fetch Soft Deleted Records in Laravel 9 ? we learnt to fetch the records from database which is soft deleted and sometimes we want to restore records that are soft deleted so to restore the trashed items in database we need to call restore method of eloquent model.

restore indicates the model that we want to restore the record which is soft deleted. we can use as follow

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

restore also worked with relationships for example we want restore all users along with soft deleted roles then we can use as below

$user->roles()->withTrashed()->restore();

But make sure you have enable the Soft delete trait in model as below

Illuminate\Database\Eloquent\SoftDeletes

This trait instruct the eloquent model to exclude the trashed data while querying from the database so we will only get the data which is not deleted means we don’t need to do any extra efforts to tell laravel its deleted this trait Illuminate\Database\Eloquent\SoftDeletes will handle everything and restore accordingly.

In this article I am going to create route, one controller, model and migrations file to learn the soft delete functionality.

Let’s start fetch Soft Deleted Records in Laravel 9 with simple step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

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

You can also read this to start with new project

Step 2 : Create a table and model

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-jwt
DB_USERNAME=root
DB_PASSWORD=

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

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

class Article extends Model
{
   use SoftDeletes;
   use HasFactory;
    
}

things to note here is we have added Illuminate\Database\Eloquent\SoftDeletes; and then used in class article as below

use SoftDeletes;

and migration file database/migrations/timestamp_create_articles_table.php

<?php

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

return class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }

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

Make sure you have added $table->softDeletes(); line in your migration to create the deleted_at column in table.

$table->softDeletes();

and then migrate the migration

php artisan migrate

Step 3 : Create controller

Let’s create a controller and add a methods showArticle and addArticle

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    public function showArticle(Request $request)
    {

        $articles = new Article;
        $articles = $articles->when($request->show_trashed=='1',function($q){
          $q->withTrashed();
        })->get();
         //or we can use directly if don't want it conditionally as below
       // $articles->withTrashed()->get();
        return view('articles.article', ['articles' => $articles]);
    }

     

    function deleteArticle(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'id' => "required",
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }
        Article::find($request->id)->delete();
        return back()
            ->with('success', 'Article deleted successfully');
    }
    
    function restoreArticle(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'id' => "required",
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }
        Article::withTrashed()->find($request->id)->restore();
        return back()
            ->with('success', 'Article restored successfully');
    }
}

Step 4 : Create View File

Now, show the upload form in view file and also show the list of compressed images

resources/views/articles/article.blade.php

<!DOCTYPE html>
<html>

<head>
    <title>How to Restore Soft Deleted Records in Laravel 9 - readerstacks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2>How to Restore Soft Deleted Records in Laravel 9 - readerstacks.com</h2>
            </div>
            <div class="panel-body">

                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                </div>

                @endif
                <br><br>
                  
                <h2>All Articles</h2>
                 <a  href="{{url('articles?show_trashed=1')}}" class="btn btn-success">Show with Trashed</a>
            
                <table class="table">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>

                        <th>Action</th>

                    </tr>
                    @foreach( $articles as $article)
                    <tr>
                        <td>{{$article->title}}</td>
                        <td>
                        {{$article->email}}
                        </td>
                        <td>
                        @if(!$article->trashed())
                          <a class='btn btn-danger' href="{{url('delete-article?id='.$article->id)}}">Delete</a>
                        @endif   
                         @if($article->trashed())
                          <a  class='btn btn-success' href="{{url('restore-article?id='.$article->id)}}">Restore</a>
                         @endif   
                       </td>
                    </tr>
                    @endforeach
                </table>
            </div>
        </div>
    </div>
</body>
</html>


create another view for show all

Step 4: Create routes in routes/web.php

One route for show all articles, another route for delete the article and restore the article.

routes/web.php

<?php

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


Route::get('/articles',[ArticleController::class,"showArticle"]);
Route::get('/delete-article',[ArticleController::class,"deleteArticle"]);
Route::get('/restore-article',[ArticleController::class,"restoreArticle"]);

Results Screenshot:

Leave a Reply