ItSolutionStuff.com

Laravel Eloquent Find with Trashed Record Example

By Hardik Savani • November 18, 2024
Laravel

In this post, I will show you how to find record with trashed record laravel application. we will find record with soft deleted in laravel app.

I will use the `find` method to retrieve a single post from the `Post` model. In this example, I'll also include soft-deleted records by using the `withTrashed()` method to access both deleted and non-deleted posts.

so, let's see the Post model and example code:

Here, is a post model code:

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;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ["title", "body"];
}

You can retrieve a single post with trashed record.

Example 1:

<?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);
    }
}

Example 2:

<?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()->findOrFail($id);
    }
}

i hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to use new Dumpable Trait in Laravel 11?

Read Now →

Laravel Eloquent Relationship withTrashed() Method Example

Read Now →

Laravel Eloquent Where Not Equal To Condition Example

Read Now →

Laravel Eloquent addSelect() Method Example

Read Now →

How to Use Google Translator in Laravel?

Read Now →

Laravel Eloquent without() and withOnly() Method Example

Read Now →

Laravel Eloquent whereHas() Condition Example

Read Now →

Laravel Eloquent Select Single Column to Array Example

Read Now →

Laravel Eloquent Model Custom Function Example

Read Now →

Laravel Eloquent updateOrCreate Example

Read Now →

Laravel Eloquent firstOrCreate Example

Read Now →

Laravel Eloquent Delete Record By ID Example

Read Now →