Laravel Eloquent Find with Trashed Record Example

Sovary December 1, 2024 62
3 minutes read

Laravel’s Eloquent ORM makes it easy to interact with your database using an expressive and elegant syntax. When working with databases, you might want to "soft delete" records—meaning, instead of permanently removing them, you mark them as deleted but retain them in the database for potential recovery later. This feature is made possible with Laravel’s SoftDeletes trait. However, by default, when you use the find method in Laravel, it won’t retrieve soft-deleted (or trashed) records. In this blog post, we’ll explore how to retrieve trashed records using Laravel Eloquent, including how to find them, restore them, and check their status.

Setting Up SoftDeletes

Before we dive into the code, make sure you have the SoftDeletes trait enabled in your Eloquent model. This trait provides functionality for soft deleting records.

How to Find with Trashed Record using Laravel Eloquent

Following steps below help you to find trashed record.

  • Step 1 - Install Laravel  App
  • Step 2 - Use the SoftDeletes Trait
  • Step 3 - Run the Migration
  • Step 4 - Create Controller

Step 1 - Install Laravel

You have to installed Laravel 11 framework. Read this to know how to install Laravel project.

Step 2: Use the SoftDeletes Trait

Run command below to create model

php artisan make:model Post

In your model (for example, Post), add the SoftDeletes trait like this:

Open file 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;
}

Also, make sure your database table has a deleted_at column. If you haven't already created this column, you can add it via a migration:

php artisan make:migration add_deleted_at_to_posts_table --table=posts

Then, in the migration file, add:

public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->softDeletes();  // Adds the deleted_at column
    });
}

Step 3: Run the Migration

php artisan migrate

With this setup in place, you can start using soft deletes in your application.

Step 4: Create Controller

To retrieve a record, including trashed records, use the withTrashed() method. This allows you to fetch both active and soft-deleted records.

php artisan make:controller PostController

Open file app -> Http -> Controllers -> PostController.blade.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $post = Post::withTrashed()->find($id);
    }
}

More Understanding

  • Checking if the Record is Trashed

Once you have the post, you may want to check whether the record is soft-deleted. To do this, you can use the trashed() method.

if ($post->trashed()) {
    echo "This post is trashed.";
} else {
    echo "This post is active.";
}

This method returns true if the record is trashed and false if it's active.

  • Restoring a Soft-Deleted Record

If you want to restore a soft-deleted record, Eloquent makes it simple with the restore() method. Here's how you can restore a trashed post:

if ($post && $post->trashed()) {
    $post->restore();
    echo "Post restored successfully.";
}
  • Retrieving Only Trashed Records

If you want to retrieve only the trashed records, you can use the onlyTrashed() method. This allows you to fetch only the records that have been soft-deleted.

Example:

$trashedPosts = Post::onlyTrashed()->get();

foreach ($trashedPosts as $trashedPost) {
    echo $trashedPost->title . "<br>";
}

Laravel's SoftDeletes functionality is a powerful tool for managing records in your application without permanently deleting them. By using methods like withTrashed(), trashed(), and onlyTrashed(), you can easily interact with trashed records. This feature is especially useful when you want to provide users with the ability to recover or view deleted data. To make your application even more robust, you can implement soft deletes in your Eloquent models and provide a smooth way to manage data without the risk of losing it permanently.

If you’re interested in learning more about Laravel Eloquent or other database features, stay tuned for more tutorials and tips! please have a nice day!!

Laravel  Laravel 11 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him