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
How to Install LibreOffice in Ubuntu 24.04
How to Install LibreOffice in...

LibreOffice is a powerful and free office suite that includes Writer, Calc, Impress, and more. It is a great alternative...

Read More

Feb-20-2025

How to Upgrade from Angular 16 to Angular 17
How to Upgrade from Angular 16...

Hey everyone! If you're a developer working with Angular, you know how exciting it is when a new version is released...

Read More

Mar-18-2024

How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021

VPS Servers - Take a Step Ahead to More Growth
VPS Servers - Take a Step Ahea...

It is the poor hosting that is causing you so many issues. If you upgrade to advanced hosting based on your website need...

Read More

Apr-08-2022