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...