Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to fetch Soft Deleted Records in Laravel 9

How to Fetch Soft Deleted Records in Laravel ?

Aman Jain, June 17, 2022June 21, 2022

In this article we will learn to fetch soft deleted records in Laravel. In our recent article Use Soft Delete to Temporary (Trash) Delete the Records in Laravel ? we learnt to delete the file without actually deleting from database and sometimes we want to show records that are soft deleted so to fetch the trashed items from database we need to call withTrashed method of eloquent model.

withTrashed indicates the model that we want to fetch all records along with soft deleted. As we know Soft delete in laravel is use to hide the record from users by keeping the data in the database.

User::withTrashed()->get();

withTrashed also worked with relationships for example we want fetch all users along with soft deleted roles then we can use as below

$user->roles()->withTrashed()->get();

But make sure you have enable the Soft delete trait in model as below

Illuminate\Database\Eloquent\SoftDeletes

This trait instruct the eloquent model to exclude the trashed data while querying from the database so we will only get the data which is not deleted means we don’t need to do any extra efforts to tell laravel its deleted this trait Illuminate\Database\Eloquent\SoftDeletes will handle everything.

In this article I am going to create route, one controller, model and migrations file to learn the soft delete functionality.

Let’s start fetch Soft Deleted Records in Laravel with simple step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2 : Create a table and model

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-jwt
DB_USERNAME=root
DB_PASSWORD=

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
   use SoftDeletes;
   use HasFactory;
    
}

things to note here is we have added Illuminate\Database\Eloquent\SoftDeletes; and then used in class article as below

use SoftDeletes;

and migration file database/migrations/timestamp_create_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticle extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

Make sure you have added $table->softDeletes(); line in your migration to create the deleted_at column in table.

$table->softDeletes();

and then migrate the migration

php artisan migrate

Now create seeder in database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

    	for ($i=0;$i<=100;$i++) {
            DB::table('articles')->insert([
                'title' => $faker->name,
                'body' => $faker->text,
                'email' => $faker->email,
                'updated_at' =>$faker->datetime,
                'created_at' => $faker->datetime              
            ]);
        }
        
    }
}

Run Seeder in command line

php artisan db:seed

Step 3 : Create controller

Let’s create a controller and add a methods showArticle and addArticle

php artisan make:controller ArticleController

and add the below code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;

class ArticleController extends Controller
{
    public function showArticle(Request $request)
    {

        $articles = new Article;
        $articles = $articles->when($request->show_trashed=='1',function($q){
          $q->withTrashed();
        })->get();
         //or we can use directly if don't want it conditionally as below
       // $articles->withTrashed()->get();
        return view('articles.article', ['articles' => $articles]);
    }

     

    function deleteArticle(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'id' => "required",
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }
        Article::find($request->id)->delete();
        return back()
            ->with('success', 'Article deleted successfully');
    }
}

Step 4 : Create View File

Now, show the upload form in view file and also show the list of compressed images

resources/views/articles/article.blade.php

<!DOCTYPE html>
<html>

<head>
    <title>How to fetch Soft Deleted Records in Laravel  - readerstacks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2> How to fetch Soft Deleted Records in Laravel  - readerstacks.com</h2>
            </div>
            <div class="panel-body">

                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                </div>

                @endif
                <br><br>
                  
                <h2>All Articles</h2>
                <a  href="{{url('articles?show_trashed=1')}}" class="btn btn-success">Show with Trashed</a>
                <table class="table">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>

                        <th>Action</th>

                    </tr>
                    @foreach( $articles as $article)
                    <tr>
                        <td>{{$article->title}}</td>
                        <td>
                        {{$article->email}}
                        </td>
                        <td><a href="{{url('delete-article?id='.$article->id)}}">Delete</a></td>
                    </tr>
                    @endforeach
                </table>
            </div>
        </div>
    </div>
</body>
</html>


create another view for show all

Step 4: Create two routes in routes/web.php

One route for show all articles and another route for delete the article.

routes/web.php

<?php

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;


Route::get('/articles',[ArticleController::class,"showArticle"]);
Route::get('/delete-article',[ArticleController::class,"deleteArticle"]);

Results Screenshot:

fetch soft deleted records in laravel
fetch soft deleted records in laravel
fetch soft deleted records in laravel
fetch soft deleted records in laravel

Related

Php Laravel Laravel 9 laravelsoft deletewithTrashed

Post navigation

Previous post
Next post

Related Posts

Php Laravel ajax login and register

Laravel ajax login and registration with example

December 4, 2021November 12, 2023

In Laravel 8 there is multiple ways to implement the laravel Ajax login and registration like Laravel provides its own auth with packages Jetstream, passport,sanctum, breeze and fortify. These all packages are easy to install and configure but sometimes our application requirement and design patterns are different or we can…

Read More
Laravel How to Run a Background Queue Job or Request in Laravel

How to Run a Background Queue Job or Request in Laravel ?

May 17, 2022August 20, 2022

In any website running a queue can help to increase the runtime performance of any application by running a background queue job or request in laravel. Queues are much helpful while our application performs bulk actions like mailing to thousand of users or running a heavy tasks. In laravel we…

Read More
Php Google Login or Signup in laravel 8 9

How to Implement Google Login or Signup in laravel 8 / 9 ?

March 22, 2022March 22, 2022

Google login or signup in laravel are demanding from start as it gives user to access the website in single click. Google is widely used social media platform therefore most of the users are on it and we can take leverage of it by providing the feature of login and…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version