How to use Soft Delete in Laravel 9

How to use Soft Delete in Laravel 9
How to use Soft Delete in Laravel 9

In this blog post, we will see what Soft Delete is and why we need it in our Laravel app. Soft delete in Laravel 9 tutorial step-by-step guide on how to use it.

What is Soft Delete in Laravel 9?


Easy deletion will not completely erase data from the site but will prevent data from being selected or marked the record for deletion.
For example, if we delete data from a site we will not be able to retrieve it or restore it easily and we will create a problem if it is used in our project. To prevent it Laravel provided support for the Illuminate \ Database \ Eloquent \ SoftDeletes trait enabling soft removal functionality. It means we can add soft removal to our Eloquent model.

Let’s see how it is used.

First, we need to decide which model we need to set up and add to use SoftDeletes in that model with this Illuminate \ Database \ Eloquent \ SoftDeletes feature, this feature will automatically stream deleted_at the DateTime / Carbon attribute to us.

Post Migration

Add the soft deletes() column on the posts table.

Laravel Inertia JS tutorial for beginners, build movie app.
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->softDeletes(); // add this to your table
            $table->timestamps();
        });
    }

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

When we delete data it will add the current date n time in deleted_at field. When we fetch a list of posts, the soft-deleted posts will automatically be excluded from all query results.

Post Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // add this

class Post extends Model
{
    use HasFactory, SoftDeletes; // add this
}

In the posts model we added SoftDeletes trait.

Web routes

<?php

use App\Http\Controllers\PostController;
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::get('/posts/trashed', [PostController::class, 'trashed'])->name('posts.trashed');
Route::post('/posts/trashed/{id}/restore', [PostController::class, 'trashedRestore'])->name('posts.trashed.restore');
Route::post('/posts/trashed/{id}/forse_delete', [PostController::class, 'trashedDelete'])->name('posts.trashed.destroy');
Route::resource('/posts', PostController::class);

In the routes we have created route resource for posts. Also route “get trashed” to get only trashed posts, roue post trashed restore to restore the post and route post trashed force_delete to delete a post forever.

Laravel Livewire tutorial for beginners,learn how to build movie app.
Post Controller
<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();

        return view('welcome', compact('posts'));
    }

    public function destroy(Post $post)
    {
        $post->delete();

        return back();
    }

    public function trashed()
    {
        $posts = Post::onlyTrashed()->get();

        return view('trashed', compact('posts'));
    }

    public function trashedRestore($id)
    {
        $post  = Post::onlyTrashed()->findOrFail($id);
        $post->restore();
        return back();
    }
    public function trashedDelete($id)
    {
        $post  = Post::onlyTrashed()->findOrFail($id);
        $post->forceDelete();
        return back();
    }
}

In the controller is all the logic. See the video for more.

Leave a Reply

Your email address will not be published.