How to Get Soft Deleted Records in Laravel

Websolutionstuff | Dec-12-2024 | Categories : Laravel

In this post, I’ll show you how to retrieve soft deleted records in a Laravel application. Soft deletes are a great feature in Laravel that allows you to hide records from queries without permanently removing them from the database.

But what if you need to access these hidden records? Don’t worry; Laravel makes it super easy to fetch soft deleted data when needed. Let’s explore how to get soft deleted records using simple and efficient methods.

How to Get Soft Deleted Records in Laravel

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 User extends Model
{
    use HasFactory, SoftDeletes;

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

 

Example:

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

 

Example:

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

 


You might also like:

Recommended Post
Featured Post
Multi Step Form Wizard jQuery Validation
Multi Step Form Wizard jQuery...

In this article, we will see multi step form wizard jquery validation. Here, we will learn jquery validation for mu...

Read More

Jan-30-2023

Laravel 8 Eloquent orWhereHas Condition
Laravel 8 Eloquent orWhereHas...

In this example we will see laravel 8 eloquent orWhereHas() condition. In previous example we will learn about ...

Read More

Oct-15-2021

Laravel 9 Livewire Datatable Example
Laravel 9 Livewire Datatable E...

In this article, we will see the laravel 9 livewire datatable example. Here, we will learn how to use livewire data...

Read More

Nov-30-2022

Laravel Rollback Targeted Migration Reversals
Laravel Rollback Targeted Migr...

As a Laravel developer, I understand the significance of migrations in managing database changes and maintaining a consi...

Read More

May-29-2023