Laravel Eloquent Find with Trashed Record Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to use new Dumpable Trait in Laravel 11?
- Laravel Eloquent Relationship withTrashed() Method Example
- Laravel Eloquent Where Not Equal To Condition Example
- Laravel Eloquent addSelect() Method Example
- How to Use Google Translator in Laravel?
- Laravel Eloquent without() and withOnly() Method Example
- Laravel Eloquent whereHas() Condition Example
- Laravel Eloquent Select Single Column to Array Example
- Laravel Eloquent Model Custom Function Example
- Laravel Eloquent updateOrCreate Example
- Laravel Eloquent firstOrCreate Example
- Laravel Eloquent Delete Record By ID Example