Delete and restore in laravel

Laravel provides a built-in feature to flag database rows as deleted without deleting them from the database. In this artisan we will see how soft delete and restore works in Laravel.

Why to Use Soft Delete?

Sometimes we need to delete some data from database but we will need those data again when required or temporary block those data from being used then soft delete comes into limelight. Restoring data is too painful process when working with live database so soft delete can handy into restoring data.

When user delete some data accidentally then it will be messy to restore that data but with soft delete we can achieve it easily.

In this example, we will create Model for Post and perform Soft delete and restore on it. In Addition we will see force delete too. So let's create model for testing

Post Model and Migration

First of all let's create Post Model and migration. you will use Soft delete into this model.

Soft delete use Laravel Illuminate\Database\Eloquent\SoftDeletes trait. So you need to import it into our application. Also you need to add use statement to use this trait into your application

    
php artisan make:model Post -m
    

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;

    public $fillable = [
        'title',
        'content',
        'category',
    ];

    protected $dates = ['deleted_at'];
}
    

In this model you just need to make few change so it can work with soft delete. First of all import SoftDeletes trait and use it into you model. then you just add required fields to into fillable and type cast deleted_at.

Now your model is ready to use soft delete and restore. There is one more thing to is add deleted_at column into your database table. Make changes to you post migration file and add delete_at column using softDeletes() function.

database\migrations\2020_11_16_034333_create_posts_table.php

    
<?php

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

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->string('category');
            $table->softDeletes();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
    

Now your Post model is ready to use soft delete and restore functionality. You can use model normally to get data. like below example :

    
//Get Post By ID
$post = Post::find(1);

//Get all posts
$posts = Post::all();

//Get post by category
$category_posts = Post::where('category',$category)->get()->json();
    

Delete Model using Soft Delete

Soft delete doesn't affect any other methods. But when you use delete method then it will update delete_at column for that record. like below example :

    
$post = Post::find(1)->detete();
    

It will update deleted_at column of that row and when you try to fetch data again it will skip those records where delete_at is not NULL,


Get Soft Deleted records

    
$deleted_posts = Post::withTrashed()->get();
    

This query will return all deleted record. You can restore those records as per your requirement.

Restoring Deleted records

You can restore deleted records as per your requirements. To restore deleted record you need to use restore() method in Laravel.

    
//Restore all Deleted Posts
$deleted_posts = Post::withTrashed()->get()->restore();

//Restore specific with pecific condition
$data = Post::withTrashed()->where('category',$category)->first()->restore();
    

Permanently Deleting Models

Sometimes you want to delete data permenentaly from our database. you can achieve those using forceDelete() method.

    
Post::find(1)->forceDelete();
    

You may also use the forceDelete method when building Eloquent relationship queries:

    
Post::find(1)->history()->forceDelete();
    

You can leave comments, suggestions, and reactions.


Share your thoughts

Ask anything about this examples